package com.crm.system.service.impl.orderManager;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.MessageManager.Message;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractManager.CustomerContractDeveloper;
import com.crm.model.entity.customerManager.*;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerOrderActivityRelation;
import com.crm.model.entity.orderManager.CustomerOrderInvoice;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.orderManager.CustomerProductOrderDetail;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.returnMoney.ReturnMoney;
import com.crm.model.entity.returnMoney.ReturnMoneyLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.entity.systemManager.SysParameterSetting;
import com.crm.model.qo.contractManager.CustomerContractAddQO;
import com.crm.model.qo.customerManager.BackMoneyQO;
import com.crm.model.qo.customerManager.OrderBackMoneyQO;
import com.crm.model.qo.messageManager.MessageAddQO;
import com.crm.model.qo.orderManager.CustomerProductOrderAddQO;
import com.crm.model.qo.orderManager.CustomerProductOrderQO;
import com.crm.model.qo.orderManager.FinanceProductOrderQO;
import com.crm.model.vo.customerManager.*;
import com.crm.model.vo.datasearch.DataSearchResultVO;
import com.crm.model.vo.finishOrderProduct.FinishOrderProductVO;
import com.crm.model.vo.orderManager.*;
import com.crm.model.vo.returnMoney.FinanceProductOderInfoVO;
import com.crm.model.vo.returnMoney.FinanceProductVO;
import com.crm.model.vo.returnMoney.ReturnMoneyVO;
import com.crm.model.vo.sendRoyaltyManager.SendRoyaltyProductVO;
import com.crm.model.vo.user.UserAccountManagerVO;
import com.crm.redis.service.returnMoneyManager.ReturnMoneyRedisService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.contractManager.CustomerContractDeveloperDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPayDbService;
import com.crm.service.customerManager.CustomerProductDetailMemberCardDbService;
import com.crm.service.customerManager.CustomerSendCodeDbService;
import com.crm.service.finishOrderProductManager.FinishOrderProductDbService;
import com.crm.service.messageManager.MessageDbService;
import com.crm.service.orderManager.*;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.returnMoney.ReturnMoneyDbservice;
import com.crm.service.returnMoney.ReturnMoneyLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.system.service.impl.csd.customerManager.CustomerServiceImpl;
import com.crm.system.service.messageManager.MessageService;
import com.crm.system.service.orderManager.CustomerProductOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ Author ：pym
 * @ Date   ：2021/3/12 10:39
 */
@Service
@Slf4j
public class CustomerProductOrderServiceImpl implements CustomerProductOrderService {

    @Autowired
    private FinishOrderProductDbService finishOrderProductDbService;

    @Autowired
    CustomerProductOrderDbService customerProductOrderDbService;

    @Autowired
    CustomerProductOrderDetailDbService customerProductOrderDetailDbService;

    @Autowired
    CustomerOrderActivityRelationDbService customerOrderActivityRelationDbService;

    @Autowired
    CustomerDbService customerDbService;

    @Autowired
    private CustomerProductDbService customerProductDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    @Autowired
    private CustomerContractDbService customerContractDbService;

    @Autowired
    private FinishOrderDBservice finishOrderDBservice;

    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;

    @Autowired
    private CustomerSendCodeDbService customerSendCodeDbService;

    @Autowired
    private SysCompanyDbService sysCompanyDbService;

    @Autowired
    private ReturnMoneyRedisService returnMoneyRedisService;

    @Autowired
    private ReturnMoneyLogDbService returnMoneyLogDbService;

    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;

    @Autowired
    private CustomerContractDeveloperDbService customerContractDeveloperDbService;

    @Autowired
    private CustomerPayDbService customerPayDbService;

    @Autowired
    private CustomerProductDetailMemberCardDbService customerProductDetailMemberCardDbService;
    
    @Autowired
    private MessageService messageService;

    @Autowired
    private CustomerServiceImpl csdCustomerServiceImpl;

    @Autowired
    private ContactDbService contactDbService;

    @Autowired
    CustomerOrderInvoiceLogDbService customerOrderInvoiceLogDbService;

    @Autowired
    private CustomerOrderInvoiceDbService customerOrderInvoiceDbService;

    /**
     * 用户模块-订单管理-订单列表
     * @Author pym
     * @Date  2021/3/12 11:08
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param customerProductOrderQO -查询条件
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @param jumpType -0：管理模块-订单管理-订单列表（超级管理员）；1：管理模块-订单管理-订单列表（普通管理员）；2：用户模块-订单管理-订单列表
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.vo.orderManager.CustomerProductOrderVO>}}
     */
    @Override
    public DhPageInfo<CustomerProductOrderVO> selectCustomerProductOrderVOList(Integer pageIndex, Integer pageSize,
                                                                               CustomerProductOrderQO customerProductOrderQO,
                                                                               String sortName, String sortOrder, String jumpType) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<CustomerProductOrderVO> customerProductOrderList = new ArrayList<CustomerProductOrderVO>();
        String accountId = userAccount.getAccountId();
        String dateType = customerProductOrderQO.getDateType();
        String companyId = userAccount.getCompanyId();
        String userId = userAccount.getUserId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //日期类型(全部/本周/本月/本年度)
        Integer dateUnit = getDateUnit(dateType);
        //排序字符串拼接
        String order = getOrder(sortName, sortOrder);
        if ("0".equals(jumpType)) { //管理模块-订单列表(超级管理员)，查询所有数据
            customerProductOrderList = customerProductOrderDbService.selectAllCustomerProductOrderList(customerProductOrderQO,
                    dateUnit, order, null, null);
        } else if ("1".equals(jumpType)) { //管理模块-订单列表(普通管理员)，查询所在公司的数据
            if (!StringUtils.isBlank(companyId)) {
                customerProductOrderList = customerProductOrderDbService.selectAllCustomerProductOrderList(customerProductOrderQO,
                        dateUnit, order, null, companyId);
            }
        } else if ("2".equals(jumpType)) { //用户模块-订单列表
            if (!StringUtils.isBlank(accountId)) {
                /*if (CommonUtils.isAdmin(userId)) { //超级管理员，查询所有数据
                    customerProductOrderList = customerProductOrderDbService.selectAllCustomerProductOrderList(customerProductOrderQO,
                            dateUnit, order, null, null);
                } else { //查询自己创建的数据
                    customerProductOrderList = customerProductOrderDbService.selectAllCustomerProductOrderList(customerProductOrderQO,
                            dateUnit, order, accountId, null);
                }*/
                if (!StringUtils.isBlank(accountId)) {
                    customerProductOrderList = customerProductOrderDbService.selectAllCustomerProductOrderList(customerProductOrderQO,
                            dateUnit, order, accountId, null);
                }
            }
        }
        PageInfo<CustomerProductOrderVO> pageInfo = new PageInfo<CustomerProductOrderVO>(customerProductOrderList);
        return new DhPageInfo<CustomerProductOrderVO>(pageInfo, customerProductOrderList);
    }

    /**
     * 日期类型(全部/本周/本月/本年度)
     * @Author pym
     * @Date  2021/3/12 16:12
     * @param dateType -(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)
     * @return {@link {java.lang.Integer}}
     */
    private Integer getDateUnit(String dateType) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("lastMonth".equals(dateType)) {
                //上月
                dateUnit = 4;
            }
        }
        return dateUnit;
    }

    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/3/15 12:32
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String sortName, String sortOrder) {
        String order = "";
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch(sortName){
                case "orderNumber":
                { //订单编号
                    order = getOrder(order, sortOrder, "order_number");
                }
                break;
                case "orderStatus":
                { //订单状态
                    order = getOrder(order, sortOrder, "order_status");
                }
                break;
                case "orderType":
                { //订单类型
                    order = getOrder(order, sortOrder, "order_type");
                }
                break;
                case "orderPaymentWay":
                { //支付方式
                    order = getOrder(order, sortOrder, "order_payment_way");
                }
                break;
                case "orderDiscountTotalAmount":
                { //订单优惠总金额
                    order = getOrder(order, sortOrder, "order_discount_total_amount");
                }
                break;
                case "orderActualTotalAmount":
                { //订单实际总金额
                    order = getOrder(order, sortOrder, "order_actual_total_amount");
                }
                break;
                case "orderTotalAmount":
                { //订单总金额
                    order = getOrder(order, sortOrder, "order_total_amount");
                }
                break;
                case "paidBackAmount":
                { //已汇款金额合计
                    order = getOrder(order, sortOrder, "paid_back_amount");
                }
                break;
                case "orderSurcharge":
                { //附加费用
                    order = getOrder(order, sortOrder, "order_surcharge");
                }
                break;
                case "orderSurchargeRemark":
                { //附加费用备注
                    order = getOrder(order, sortOrder, "order_surcharge_remark");
                }
                break;
                case "contactPerson":
                { //客户联系人
                    order = getOrder(order, sortOrder, "contact_person");
                }
                break;
                case "bindMobilePhoneNumber":
                { //客户联系方式
                    order = getOrder(order, sortOrder, "bind_mobile_phone_number");
                }
                break;
                case "customerEmail":
                { //客户邮箱
                    order = getOrder(order, sortOrder, "customer_email");
                }
                break;
                case "whetherCoDevelopment":
                { //是否合作开发
                    order = getOrder(order, sortOrder, "whether_co_development");
                }
                break;
                case "whetherAllPayment":
                { //是否全部到款
                    order = getOrder(order, sortOrder, "whether_all_payment");
                }
                break;
                case "paidBackStatus":
                { //回款状态
                    order = getOrder(order, sortOrder, "paid_back_status");
                }
                break;
                case "whetherSuspend":
                { //是否挂起
                    order = getOrder(order, sortOrder, "whether_suspend");
                }
                break;
                case "contractNumber":
                { //合同编号
                    order = getOrder(order, sortOrder, "contract_number");
                }
                break;
                case "orderCompleteTm":
                { //订单完成时间
                    order = getOrder(order, sortOrder, "order_complete_tm");
                }
                break;
                case "companyName":
                { //所属分公司
                    order = getOrder(order, sortOrder, "company_name");
                }
                break;
                case "customerName":
                { //客户名称
                    order = getOrder(order, sortOrder, "customer_name");
                }
                break;
                case "userName":
                { //创建人
                    order = getOrder(order, sortOrder, "user_name");
                }
                break;
                case "createTm":
                { //创建时间
                    order = getOrder(order, sortOrder, "create_tm");
                }
                break;
                case "salesmanName":
                { //业务员
                    order = getOrder(order, sortOrder, "user_name");
                }
                break;
                default:
                    break;
            }
        }
        if (!order.contains("create_tm")) {
            order = getOrder(order, "DESC", "create_tm");
        }
        return order;
    }

    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/3/15 11:44
     * @param order -排序字符串
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String order, String sortOrder, String sortName) {
        if (StringUtils.isBlank(order)) {
            order += sortName +" "+ sortOrder;
        } else {
            order += ","+sortName +" " + sortOrder;
        }
        return order;
    }

    /**
     * 订单详情基本信息
     * @Author pym
     * @Date  2021/3/17 11:13
     * @param productOrderId
     * @return {@link {com.crm.model.vo.orderManager.OrderDetailVO}}
     */
    @Override
    public OrderDetailVO selectOrderDetailVO(String productOrderId) {
        OrderDetailVO orderDetailVO = customerProductOrderDbService.selectOrderDetailVO(productOrderId);
        if (Objects.nonNull(orderDetailVO) && Objects.nonNull(orderDetailVO.getContractReceivables())
                && Objects.nonNull(orderDetailVO.getReturnMoneyAmount())){
            orderDetailVO.setResidueMoneyAmount(orderDetailVO.getContractReceivables().subtract(orderDetailVO.getReturnMoneyAmount()));
        }
        return orderDetailVO;
    }

    /**
     * 订单管理-订单列表-订单详情-产品详情、活动产品列表
     * @Author pym
     * @Date  2021/3/18 10:59
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param productOrderId -产品订单表主键
     * @param productOrderDetailType -订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型;4:查询产品状态为正常的
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.entity.orderManager.CustomerProductOrderDetail>}}
     */
    @Override
    public DhPageInfo<CustomerProductOrderDetail> selectCustomerProductOrderDetailList(Integer pageIndex, Integer pageSize, String productOrderId, String productOrderDetailType) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<CustomerProductOrderDetail> customerProductOrderDetails = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(productOrderId, productOrderDetailType);
        PageInfo<CustomerProductOrderDetail> pageInfo = new PageInfo<CustomerProductOrderDetail>(customerProductOrderDetails);
        return new DhPageInfo<CustomerProductOrderDetail>(pageInfo, customerProductOrderDetails);
    }

    /**
     * 财务-订单列表
     * @Author chaifuyou
     * @Date  2021/3/19 10:20
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @param financeProductOrderQO -查询条件
     * @return {@link {com.crm.common.model.DataResponse}}
     */
    @Override
    public DhPageInfo<FinanceProductOrderVO> selectFinanceOrderVOList(Integer pageIndex, Integer pageSize, FinanceProductOrderQO financeProductOrderQO, String sortName, String sortOrder, String jumpType) {
        if (Objects.nonNull(financeProductOrderQO.getDateStatusType()) && financeProductOrderQO.getDateStatusType() == 1){
            financeProductOrderQO.setOrderStatus(2);
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<FinanceProductOrderVO> customerProductOrderList = new ArrayList<FinanceProductOrderVO>();
        String accountId = userAccount.getAccountId();
        String dateType = financeProductOrderQO.getDateType();
        String companyId = userAccount.getCompanyId();
        String userId = userAccount.getUserId();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //日期类型(全部/本周/本月/本年度)
        Integer dateUnit = getDateUnit(dateType);
        //排序字符串拼接
        String order = getOrder(sortName, sortOrder);
        //3是总部财务
        if ("3".equals(userAccount.getDeptId())) {
            customerProductOrderList = customerProductOrderDbService.selectFinanceOrderVOList(financeProductOrderQO,
                    dateUnit, order,  null);
        } else if ("4".equals(userAccount.getDeptId())) { //4是分公司财务
            if (!StringUtils.isBlank(companyId)) {
                customerProductOrderList = customerProductOrderDbService.selectFinanceOrderVOList(financeProductOrderQO,
                        dateUnit, order, companyId);
            }
        }
        PageInfo<FinanceProductOrderVO> pageInfo = new PageInfo<FinanceProductOrderVO>(customerProductOrderList);
        return new DhPageInfo<FinanceProductOrderVO>(pageInfo, customerProductOrderList);
    }

    /**
     * 财务-订单详情
     * @param productOrderId
     * @return
     */
    @Override
    public FinanceProductOderInfoVO financeProductOderInfo(String productOrderId,Integer status) {
        FinanceProductOderInfoVO vo =new FinanceProductOderInfoVO();
        //优先查正常产品
        vo =customerProductOrderDbService.getFinanceProductOderInfo(productOrderId,status,1);
        if (Objects.isNull(vo)){
            vo =customerProductOrderDbService.getFinanceProductOderInfo(productOrderId,status,null);
        }
        CustomerProductOrder customerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(productOrderId);
        Integer type = 0;
        if (Objects.nonNull(customerProductOrder) && Objects.nonNull(customerProductOrder.getOrderSurcharge())){
            type = 1;
        }
        List<FinanceProductVO> productsaArr=new ArrayList<>();
        //for (int i=0;i<4;i++){
            List<FinanceProductVO> products=customerProductOrderDetailDbService.getOrderProductList(productOrderId,type);
            if (Objects.nonNull(products)){
                for (int k=0;k<products.size();k++){
                    FinanceProductVO productVO;
                    productVO =products.get(k);
                    if (Objects.nonNull(productVO) && Objects.nonNull(productVO.getMoney())&& Objects.nonNull(productVO.getProductQuantity())){
                        BigDecimal count = new BigDecimal(productVO.getProductQuantity().toString());
                        productVO.setMoney(productVO.getMoney().multiply(count));
                    }
                    productsaArr.add(productVO);
                }
            }
        //}
        if (Objects.isNull(vo)){
            vo = new FinanceProductOderInfoVO();
        }
        vo.setProducts(productsaArr);
        if (Objects.nonNull(vo) && Objects.nonNull(vo.getOrderActualTotalAmount()) && Objects.nonNull(vo.getReturnMoneyAmount())){
            vo.setResidueMoneyAmount(vo.getOrderActualTotalAmount().subtract(vo.getReturnMoneyAmount()));
        }
        //订单预回款总金额
        BigDecimal preReturnMoneyTotal = returnMoneyDbservice.queryPreReturnMoneyTotal(productOrderId,null);
        vo.setPreReturnMoneyTotal(preReturnMoneyTotal);
        return vo;
    }

    /**
     * 订单管理-订单列表-订单详情-活动产品列表-活动下的产品
     * @Author pym
     * @Date  2021/3/26 10:04
     * @param productOrderId -订单ID
     * @param orderRelationId -活动产品ID
     * @return {@link {java.util.List<java.util.HashMap>}}
     */
    @Override
    public List<HashMap> selectOrderActivityRelationProductNames(String productOrderId, String orderRelationId) {
        List<HashMap> orderActivityRelationProductNames = new ArrayList<HashMap>();
        List<CustomerOrderActivityRelation> customerOrderActivityRelationList =
                customerOrderActivityRelationDbService.selectOrderActivityRelationByOrderIdAndActivityId(productOrderId, orderRelationId);
        customerOrderActivityRelationList.stream().forEach(customerOrderActivityRelation -> {
            HashMap hashMap = new HashMap();
            hashMap.put("productName",customerOrderActivityRelation.getProductName());
            orderActivityRelationProductNames.add(hashMap);
        });
        return orderActivityRelationProductNames;
    }

    /**
     * 根據訂單id獲取訂單產品和活動信息
     * @param productOrderId
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @return
     */
    @Override
    public DhPageInfo<SendRoyaltyProductVO> financeOrderProductAndActivity(String productOrderId, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<SendRoyaltyProductVO> retustList =new ArrayList<>();
        //for (int i=1;i<3;i++){
            List<SendRoyaltyProductVO> list = customerProductOrderDetailDbService.financeOrderProductAndActivity(productOrderId,0);
            for (int k=0;k<list.size();k++){
                SendRoyaltyProductVO vo = new SendRoyaltyProductVO();
                vo = list.get(k);
                if ("2".equals(vo.getProductOrderDetailType())){
                    OrderActivityVO activityVO = customerProductOrderDetailDbService.selectActivityProductCount(vo.getOrderDetailId());
                    if (Objects.nonNull(activityVO)){
                        if (!"0".equals(activityVO.getProductCount()) && Objects.nonNull(activityVO.getActivityFinalPrice())){
                            vo.setMoney(activityVO.getActivityFinalPrice().divide(new BigDecimal(activityVO.getProductCount()),2));
                        }
                    }
                }
                retustList.add(vo);
            }
        //}
        PageInfo<SendRoyaltyProductVO> pageInfo=new PageInfo<>(retustList);
        return new DhPageInfo<SendRoyaltyProductVO>(pageInfo,retustList);
    }

    /**
     * 申请开票页面订单详情
     * @param type
     * @param orderId
     * @return
     */
    @Override
    public ApplyInvoiceOrderInfoVO getApplyInvoiceOrderInfo(String type, String orderId,String chsCustomerOrderInvoiceId) {
        ApplyInvoiceOrderInfoVO vo = customerProductOrderDbService.getApplyInvoiceOrderInfo(type,orderId);
        if(Objects.nonNull(chsCustomerOrderInvoiceId)){
            CustomerOrderInvoice orderInvoice = customerOrderInvoiceDbService.selectByPrimaryKey(chsCustomerOrderInvoiceId);
            if (orderInvoice.getExamineStatus() != 2){
                BigDecimal big = customerOrderInvoiceLogDbService.getSumApplyInvoiceMoney(chsCustomerOrderInvoiceId);
                vo.setResidueMoney(orderInvoice.getInvoiceMoney().subtract(big));
            }else {
                vo.setResidueMoney(new BigDecimal("0.00"));
            }

        }
        return vo;
    }

    /***
     * @Description:会员非会员总额度统计
     * @Param:yearMark 查询月份(传12是今年，传24是去年)
     * @Author: luojie
     * @Date: 2021/4/27 22:26
     */
    @Override
    public JSONObject selectAnnualAmount(Integer yearMark,String accountId) {

        JSONObject result = new JSONObject();

        //会员金额
        List<HashMap> memberAmountList = new ArrayList<>();
        //非会员金额
        List<HashMap> nonMemberAmountList = new ArrayList<>();
        //会员金额+分会员金额
        List<HashMap> allAmountList = new ArrayList<>();

/*        SimpleDateFormat resultSdf = new SimpleDateFormat("yyyy-MM");

        Calendar nowCal = Calendar.getInstance();
        nowCal.setTime(new Date());
        nowCal.add(Calendar.MONTH, -1 * yearMark);*/
        SimpleDateFormat timeSdf = new SimpleDateFormat("yyyy");
        Calendar nowCal = Calendar.getInstance();
        String date = "";
        if(yearMark == 12){
            //本年
            date = timeSdf.format(nowCal.getTime());
        }else{
            //去年
            nowCal.add(Calendar.YEAR,-1);
            date = timeSdf.format(nowCal.getTime());
        }
        /*if(yearMark==12){*/
            //本年
            for (int i=1; i < 13; i++) {
                String yearMonth = "";
                if(String.valueOf(i).length()==1){
                    String month = "0" + i;
                    yearMonth = date + "-" + month;
                }else {
                    yearMonth = date + "-" + String.valueOf(i);
                }

                //查询会员实际订单总金额
                //定义会员变量
                String memberTag = "1";
                BigDecimal memberAmount = customerProductOrderDbService.selectAnnualAmountByOneMonth(yearMonth,memberTag,accountId);
                HashMap memberHashMap = new HashMap();
                memberHashMap.put("yeahMonth",yearMonth);
                memberHashMap.put("memberAmount",memberAmount);
                memberAmountList.add(memberHashMap);

                //非会员
                String nonMemberTag = "0";
                BigDecimal nonMemberAmount = customerProductOrderDbService.selectAnnualAmountByOneMonth(yearMonth,nonMemberTag,accountId);
                HashMap nonMemberHashMap = new HashMap<>();
                nonMemberHashMap.put("yeahMonth",yearMonth);
                nonMemberHashMap.put("memberAmount",nonMemberAmount);
                nonMemberAmountList.add(nonMemberHashMap);

                HashMap allHashMap = new HashMap();
                allHashMap.put("yeahMonth",yearMonth);
                allHashMap.put("allAmount",memberAmount.add(nonMemberAmount));
                allAmountList.add(allHashMap);
            }

        /*}else {
            //去年
            for (int i=12; i < yearMark; i++) {
                nowCal.add(Calendar.MONTH, 1);
                //获取从当前算12个月的日期数据
                String yeahMonth = resultSdf.format(nowCal.getTime());

                //查询会员实际订单总金额
                //定义会员变量
                String memberTag = "1";
                BigDecimal memberAmount = customerProductOrderDbService.selectAnnualAmountByOneMonth(yeahMonth,memberTag,accountId);
                HashMap memberHashMap = new HashMap();
                memberHashMap.put("yeahMonth",yeahMonth);
                memberHashMap.put("memberAmount",memberAmount);
                memberAmountList.add(memberHashMap);

                //非会员
                String nonMemberTag = "0";
                BigDecimal nonMemberAmount = customerProductOrderDbService.selectAnnualAmountByOneMonth(yeahMonth,nonMemberTag,accountId);
                HashMap nonMemberHashMap = new HashMap<>();
                nonMemberHashMap.put("yeahMonth",yeahMonth);
                nonMemberHashMap.put("memberAmount",nonMemberAmount);
                nonMemberAmountList.add(nonMemberHashMap);

                HashMap allHashMap = new HashMap();
                allHashMap.put("yeahMonth",yeahMonth);
                allHashMap.put("allAmount",memberAmount.add(nonMemberAmount));
                allAmountList.add(allHashMap);
            }
        }*/

        result.put("memberAmountList",memberAmountList);
        result.put("nonMemberAmountList",nonMemberAmountList);
        result.put("allAmountList",allAmountList);
        return result;
    }

    /***
     * @Description:查询本月业绩饼图
     * @Author: luojie
     * @Date: 2021/4/27 22:46
     */
    @Override
    public JSONObject selectThisMonthPerformance(String accountId) {
        SimpleDateFormat resultSdf = new SimpleDateFormat("yyyy-MM");
        String thisMonth = resultSdf.format(new Date());
        JSONObject result = new JSONObject();
        //当前用户customerController
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //公司业绩值
        BigDecimal companyPerformance =  customerProductOrderDbService.selectThisMonthCompanyPerformance(userAccount.getCompanyId(),thisMonth);
        //个人业绩值
        BigDecimal PersonalPerformance =  customerProductOrderDbService.selectThisMonthPersonalPerformance(accountId,thisMonth);
        //查询个人本月业绩统计
        int personPerformanceRank = customerProductOrderDbService.personalThisMonthPerformanceRank(userAccount.getCompanyId(),accountId,thisMonth);

        result.put("companyPerformance",companyPerformance);
        result.put("PersonalPerformance",PersonalPerformance);
        result.put("personPerformanceRank",personPerformanceRank);
        return result;
    }

    /***
     * @Description:查询业绩排名
     * @Author: luojie
     * @Date: 2021/4/29 9:23
     */
    @Override
    public List<PerformanceRankVO> selectPerformanceRank() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<PerformanceRankVO> result = customerProductOrderDbService.selectPerformanceRank(userAccount.getCompanyId());
        return result;
    }

    /***
     * @Description:根据个人id和时间范围统计合同信息
     * @Param: accountId 用户id
     * @Param: timeTag 时间标识
     * @Author: luojie
     * @Date: 2021/4/29 13:53
     */
    @Override
    public JSONObject selectStatisticsContractInformation(String dateType, String accountId) {
        JSONObject jsonObject = new JSONObject();

        Integer dateUnit = 0;

        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("firstMonth".equals(dateType)) {
                //上月
                dateUnit = 3;
            }
        }
        //未生效合同额度（订单状态--1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）
        String orderStatus = "1";
        BigDecimal invalidContractQuota = customerProductOrderDbService.selectContractAmount(orderStatus,dateUnit, accountId);
        jsonObject.put("invalidContractQuota",invalidContractQuota);
        //未生效合同个数
        long invalidContractCount= customerProductOrderDbService.selectContractCount(orderStatus,dateUnit, accountId);
        jsonObject.put("invalidContractCount",invalidContractCount);
        //生效合同额度
        orderStatus = "2";
        BigDecimal effectiveContractQuota = customerProductOrderDbService.selectContractAmount(orderStatus,dateUnit, accountId);
        jsonObject.put("effectiveContractQuota",effectiveContractQuota);
        //生效合同个数
        long effectiveContractCount= customerProductOrderDbService.selectContractCount(orderStatus,dateUnit, accountId);
        jsonObject.put("effectiveContractCount",effectiveContractCount);

        //作废合同数
        orderStatus = "3";
        long abolitionContractCount= customerProductOrderDbService.selectContractCount(orderStatus,dateUnit, accountId);
        jsonObject.put("abolitionContractCount",abolitionContractCount);
        //开票合同数
        int invoiceContractCount = 0;
        jsonObject.put("invoiceContractCount",invoiceContractCount);
        //冲红合同数
        int redContractCount = 0;
        jsonObject.put("redContractCount",redContractCount);
        //退款合同数
        long refundContractCount = customerProductOrderDbService.selectContractRefundCount(dateUnit,accountId);
        jsonObject.put("refundContractCount",refundContractCount);
        //合同作废率
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        String contractAbolitionRate = "0";
        if(abolitionContractCount != 0 && effectiveContractCount != 0){
            contractAbolitionRate = numberFormat.format((float)abolitionContractCount/(float)effectiveContractCount);
        }
        jsonObject.put("contractAbolitionRate",contractAbolitionRate + "%");
        jsonObject.put("contractAbolitionValue","较低");
        //合同退款率
        String contractRefundRate = "0";
        if(refundContractCount != 0 && effectiveContractCount != 0){
            contractRefundRate = numberFormat.format((float)refundContractCount/(float)effectiveContractCount);
        }
        jsonObject.put("contractRefundRate",contractRefundRate + "%");
        jsonObject.put("contractRefundValue","较低");
        //发票冲红率
        String invoiceRedRate = "0";
        if(redContractCount !=0 && effectiveContractCount != 0){
            invoiceRedRate = numberFormat.format((float)redContractCount/(float)effectiveContractCount);
        }
        jsonObject.put("invoiceRedRate",invoiceRedRate + "%");
        jsonObject.put("invoiceRedValue","较低");
        return jsonObject;
    }


    /**
     * @Description: 通过订单编号获取数据
     * @Param: [orderNum]
     * @Return: java.util.List<com.crm.model.vo.datasearch.DataSearchResultVO>
     * @Author: lixq-f
     * @Date: 2021/5/13
     **/
    @Override
    public List<DataSearchResultVO> selectDataByOrderNum(String orderNum) {
        return customerProductOrderDbService.selectDataByOrderNum(orderNum);
    }

    
    /**
     * 申请退款(业务员端)
     * @Author bj
     * @Date  2021/7/27 9:27
     */
    @Override
    public String orderRefund(CustomerOrderBackMoney customerProductOrderDetail) {

        Calendar now = Calendar.getInstance();
        if(now.get(Calendar.DAY_OF_MONTH) < 11) {
            return "每月1到10号不能申请退款!";
        }

        if(customerProductOrderDetail.getApplyBackMoney().compareTo(BigDecimal.ZERO) < 1) {
            return "申请退款金额要大于0!";
        }

        SysParameterSetting sysParameterSetting = contactDbService.selectContactCodeStatus();
        //退款控制  Y-打开，N-关闭
        if("N".equals(sysParameterSetting.getRefundSwitch())) {
            return "退款控制已关闭!";
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerProductOrder customerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(customerProductOrderDetail.getProductOrderId());
        CustomerOrderBackMoney orderBackMoney = new CustomerOrderBackMoney();
        if("2".equals(customerProductOrder.getOrderStatus())) {


            BigDecimal backMoney = customerProductOrderDbService.sumBackMoney(customerProductOrderDetail.getProductOrderId(), customerProductOrderDetail.getFinishOrderProductNum());

            if (backMoney != null) {
                backMoney = backMoney.add(customerProductOrderDetail.getApplyBackMoney());
            } else {
                backMoney = customerProductOrderDetail.getApplyBackMoney();
            }

            if (backMoney.compareTo(customerProductOrderDetail.getProductFinalPrice()) == 1) {
                return "您的退款全部金额不能大于产品成交价!";
            }

            if ("附加费用".equals(customerProductOrderDetail.getProductName())) {
                CustomerOrderBackMoney customerOrderBackMoney = customerProductOrderDbService.selectBackMoneyFjfy("附加费用", customerProductOrderDetail.getProductOrderId());
                if (customerOrderBackMoney != null) {
                    return "附加费用已经在退款记录中,请联系财务人员处理";
                }
            } else {
                List<CustomerOrderBackMoney> list = customerProductOrderDbService.selectCustomerOrderBackMoneyByCph(customerProductOrderDetail.getFinishOrderProductNum(), 2);
                if (list != null && list.size() > 0) {
                    if (list.size() == 1) {
                        orderBackMoney = list.get(0);
                        if (orderBackMoney != null) {
                            return "你的产品名称为" + customerProductOrderDetail.getProductName() + "已经在退款记录中,请联系财务人员处理";
                        }
                    }
                }
            }
        }
        if("4".equals(customerProductOrder.getOrderStatus())) {

//            BigDecimal bigDecimal = orderProductDetailNumMoney(customerProductOrder.getProductOrderId());
//            if(customerProductOrderDetail.getApplyBackMoney().compareTo(bigDecimal) == 0) {
//                return "申请退款金额必须全额";
//            }

            orderBackMoney = customerProductOrderDbService.selectCustomerOrderBackMoneyByOrderId(customerProductOrderDetail.getProductOrderId(),0);
            if(orderBackMoney != null) {
                return "你的订单已经在退款记录中,请联系财务人员处理";
            }
        }

        CustomerOrderBackMoney customerOrderBackMoney = new CustomerOrderBackMoney();
        customerOrderBackMoney.setOrderBackMoneyId(CommonUtils.getGUID());
        customerOrderBackMoney.setBackNumber(String.valueOf(new Date().getTime()));
        customerOrderBackMoney.setProductOrderId(customerProductOrderDetail.getProductOrderId());
        customerOrderBackMoney.setOrderStatus(customerProductOrder.getOrderStatus());
        if("2".equals(customerProductOrder.getOrderStatus())) {

            if("附加费用".equals(customerProductOrderDetail.getProductName())) {
                customerOrderBackMoney.setProductName(customerProductOrderDetail.getProductName());
                customerOrderBackMoney.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice());
            }else{
                customerOrderBackMoney.setProductCode(customerProductOrderDetail.getProductCode());
                customerOrderBackMoney.setFinishOrderProductNum(customerProductOrderDetail.getFinishOrderProductNum());
                customerOrderBackMoney.setProductName(customerProductOrderDetail.getProductName());
                customerOrderBackMoney.setProductOriginalPrice(customerProductOrderDetail.getProductOriginalPrice());
                customerOrderBackMoney.setProductUnitPrice(customerProductOrderDetail.getProductUnitPrice());
                customerOrderBackMoney.setProductMemberPrice(customerProductOrderDetail.getProductMemberPrice());
                customerOrderBackMoney.setProductPreferentialPrice(customerProductOrderDetail.getProductPreferentialPrice());
                customerOrderBackMoney.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice());
            }
            customerOrderBackMoney.setCommissionStatus(1);

        }
        Customer customer = customerDbService.selectCustomerById(customerProductOrder.getCustomerId());
        if(customer != null) {
            customerOrderBackMoney.setCustomerId(customer.getCustomerId());
            customerOrderBackMoney.setCustomerName(customer.getCustomerName());
            customerOrderBackMoney.setCustomerNumber(customer.getCustomerNumber());
        }

        customerOrderBackMoney.setSqbz(customerProductOrderDetail.getSqbz());
        customerOrderBackMoney.setApplyBackMoney(customerProductOrderDetail.getApplyBackMoney());
        customerOrderBackMoney.setCreatePeopleId(userAccount.getAccountId());
        customerOrderBackMoney.setCreateTm(new Date());
        customerOrderBackMoney.setAccountId(userAccount.getAccountId());
        customerOrderBackMoney.setCompanyId(userAccount.getCompanyId());

        customerProductOrderDbService.addCustomerOrderBackMoney(customerOrderBackMoney);


        CustomerOrderBackMoneyExamine examine = new CustomerOrderBackMoneyExamine();
        examine.setOrderBackMoneyExamineId(CommonUtils.getGUID());
        examine.setAdoptSituation(0);
        examine.setFzExamineStatus(0);
        examine.setCreatePeopleId(userAccount.getAccountId());
        examine.setCreateTm(new Date());
        examine.setUpdatePeopleId(userAccount.getAccountId());
        examine.setUpdateTm(new Date());
        examine.setAccountId(userAccount.getAccountId());
        examine.setCompanyId(userAccount.getCompanyId());
        examine.setOrderBackMoneyId(customerProductOrderDetail.getOrderBackMoneyId());
        customerProductOrderDbService.addCustomerOrderBackMoneyExamine(examine);


        return "success";
    }

    /**
     * 余额申请退款(业务员端)
     * @Author bj
     * @Date  2021/7/27 9:27
     */
    @Override
    public String balanceRefund(CustomerOrderBackMoney customerOrderBackMoney) {

        /*Calendar now = Calendar.getInstance();
        if(now.get(Calendar.DAY_OF_MONTH) < 11) {
            return "每月1到10号不能申请退款!";
        }*/

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        customerOrderBackMoney.setOrderBackMoneyId(CommonUtils.getGUID());
        customerOrderBackMoney.setBackNumber(String.valueOf(new Date().getTime()));
        Customer customer = customerDbService.selectCustomerById(customerOrderBackMoney.getCustomerId());
        if(customer != null) {
            if(customer.getCustomerWallet().compareTo(customerOrderBackMoney.getApplyBackMoney()) == -1) {
                return "余额不足!";
            }
            customerOrderBackMoney.setCustomerId(customer.getCustomerId());
            customerOrderBackMoney.setCustomerName(customer.getCustomerName());
            customer.setCustomerNumber(customer.getCustomerNumber());
        }

        customerOrderBackMoney.setSqbz(customerOrderBackMoney.getSqbz());
        customerOrderBackMoney.setApplyBackMoney(customerOrderBackMoney.getApplyBackMoney());
        customerOrderBackMoney.setRefundType(1);
        customerOrderBackMoney.setCreatePeopleId(userAccount.getAccountId());
        customerOrderBackMoney.setCreateTm(new Date());
        customerOrderBackMoney.setAccountId(userAccount.getAccountId());
        customerOrderBackMoney.setCompanyId(userAccount.getCompanyId());
        customerProductOrderDbService.addCustomerOrderBackMoney(customerOrderBackMoney);

        CustomerOrderBackMoneyExamine examine = new CustomerOrderBackMoneyExamine();
        examine.setOrderBackMoneyExamineId(CommonUtils.getGUID());
        examine.setAdoptSituation(0);
        examine.setFzExamineStatus(0);
        examine.setCreatePeopleId(userAccount.getAccountId());
        examine.setCreateTm(new Date());
        examine.setUpdatePeopleId(userAccount.getAccountId());
        examine.setUpdateTm(new Date());
        examine.setAccountId(userAccount.getAccountId());
        examine.setCompanyId(userAccount.getCompanyId());
        examine.setOrderBackMoneyId(customerOrderBackMoney.getOrderBackMoneyId());
        customerProductOrderDbService.addCustomerOrderBackMoneyExamine(examine);

        if(customer != null) {
            customer.setCustomerWallet(customer.getCustomerWallet().subtract(customerOrderBackMoney.getApplyBackMoney()));
            customer.setUpdatePeopleId(userAccount.getAccountId());
            customer.setUpdateTm(new Date());
            customerDbService.updateCustomerById(customer);
        }
        return "SUCCESS";
    }

    /**
     * 通过退款id查询退款审核表
     * @param orderBackMoneyId 退款id
     * @return
     */
    @Override
    public CustomerOrderBackMoneyExamine selectOrderBackMoneyExamine(String orderBackMoneyId) {
        return customerProductOrderDbService.selectOrderBackMoneyExamine(orderBackMoneyId);
    }


    /**
     * 客户-退款列表
     * @Author bj
     * @Date  2021/7/27 9:27
     */
    @Override
    public DhPageInfo<CustomerOrderBackMoneyVO> customerOrderBackMoneyList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder,OrderBackMoneyQO orderBackMoneyQO) {

        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        boolean rs = false;
        if("3".equals(userAccount.getDeptId())){
            rs = true;
        }

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(orderBackMoneyQO.getDateType())) {
            if ("thisWeek".equals(orderBackMoneyQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(orderBackMoneyQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("day".equals(orderBackMoneyQO.getDateType())) {
                //今天
                dateUnit = 3;
            }
        }

        orderBackMoneyQO.setDateUnit(dateUnit);




        List<CustomerOrderBackMoneyVO> list = new ArrayList<>();
        if((orderBackMoneyQO.getAdoptSituation()) != 5) {
            if(rs) {
                //超级管理员
                orderBackMoneyQO.setType(0);
                list = customerProductOrderDbService.superCustomerOrderBackMoneyList(orderBackMoneyQO);
            }else {
                //普通管理员
                orderBackMoneyQO.setType(1);
                orderBackMoneyQO.setName(userAccount.getCompanyId());
                list = customerProductOrderDbService.customerOrderBackMoneyList(orderBackMoneyQO);
            }
        }else {
            //普通用户
            //orderBackMoneyQO.setType(2);
            orderBackMoneyQO.setName(userAccount.getAccountId());
            list = customerProductOrderDbService.userCustomerOrderBackMoneyList(orderBackMoneyQO);
        }

        PageInfo<CustomerOrderBackMoneyVO> pageInfo=new PageInfo<>(list);
        return new DhPageInfo<CustomerOrderBackMoneyVO>(pageInfo,list);
    }

    /**
     * 时间比较
     * @param date
     * @return
     */
    public boolean compare(Date date) {
        Date sd1 = null;
        try{
            String beginTime=new String("2021-09-10 00:00:00");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sd1 =df.parse(beginTime);
            //a>b  false   a<b true
        }catch (Exception e) {
            e.printStackTrace();
        }
        return sd1.before(date);
    }

    /**
     *财务-退款详情
     * @param orderBackMoneyId 退款id
     * @param productOrderId 订单id
     * @return
     */
    @Override
    public Map<String, Object> customerOrderBackMoneyDetail(String orderBackMoneyId, String productOrderId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        Map<String, Object> map = new HashMap<>();

        //订单详细信息
        OrderDetailVO orderDetailVO = customerProductOrderDbService.selectBackOrderDetail(orderBackMoneyId);

        //退款明细
        CustomerOrderBackMoney customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(orderBackMoneyId);

        //a>b  false   a<b true    2021-09-10
//        Boolean bs = compare(customerOrderBackMoney.getBackDate());
//        if(bs) {
//            map.put("examineBs",true);
//        }else{
//            map.put("examineBs",false);
//        }

        ReturnMoney returnMoney = customerProductOrderDbService.selectReturnByRoyaltyStatus(productOrderId,1);
        if(returnMoney != null) {
            map.put("royaltyStatus","已发放");
        }else{
            map.put("royaltyStatus","未发放");
        }

        //退款审批表
        CustomerOrderBackMoneyExamine examine = customerProductOrderDbService.selectOrderBackMoneyExamine(orderBackMoneyId);
        if(0 == customerOrderBackMoney.getBackStatus()) {
            if(examine == null) {
                examine = new CustomerOrderBackMoneyExamine();
                examine.setOrderBackMoneyExamineId(CommonUtils.getGUID());
                examine.setAdoptSituation(0);
                examine.setFzExamineStatus(0);
                examine.setCreatePeopleId(userAccount.getAccountId());
                examine.setCreateTm(new Date());
                examine.setUpdatePeopleId(userAccount.getAccountId());
                examine.setUpdateTm(new Date());
                examine.setAccountId(userAccount.getAccountId());
                examine.setCompanyId(userAccount.getCompanyId());
                examine.setOrderBackMoneyId(orderBackMoneyId);
                customerProductOrderDbService.addCustomerOrderBackMoneyExamine(examine);
            }
        }

        /*if(!"附加费用".equals(customerOrderBackMoney.getProductName())) {
            if("2".equals(orderDetailVO.getOrderStatus())) {
                FinishOrderProduct finishOrderProduct = finishOrderDBservice.selectFinshByProductNum(customerOrderBackMoney.getFinishOrderProductNum());
                map.put("productStatus",finishOrderProduct);
            }
            if("4".equals(orderDetailVO.getOrderStatus())) {
                List<CustomerProductOrderDetail> customerProductOrderDetails = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(productOrderId, "1");
                map.put("productStatus",customerProductOrderDetails);
            }
        }*/


        map.put("order",orderDetailVO);
        map.put("orderBackMoneyExamine",examine);

        if(examine != null) {
            if(0 == examine.getAdoptSituation()) {
                map.put("status",examine.getFzExamineStatus());
            }else if(1 == examine.getAdoptSituation()) {
                map.put("status",examine.getKfExamineStatus());
            }else if(2 == examine.getAdoptSituation()) {
                map.put("status",examine.getXzExamineStatus());
            }else if(3 == examine.getAdoptSituation()) {
                map.put("status",examine.getWlbExamineStatus());
            }else if(4 == examine.getAdoptSituation()) {
                map.put("status",examine.getCwExamineStatus());
            }else{
                map.put("status",null);
            }
        }


        CustomerProductDetailMemberCardVO customerProductDetailMemberCardVO = new CustomerProductDetailMemberCardVO();
        //已完成
        if("2".equals(customerOrderBackMoney.getOrderStatus())) {
            List<CustomerOrderBackMoney> list = new ArrayList<>();
            list.add(customerOrderBackMoney);
            map.put("customerOrderBackMoney",list);

            if(!StringUtils.isBlank(customerOrderBackMoney.getFinishOrderProductNum())) {
                //会员卡
                List<CustomerProductDetailMemberCard> cardList = customerDbService.getMemberCardByOrderIdAndCph(productOrderId, customerOrderBackMoney.getFinishOrderProductNum()+"CCC");
                if (cardList != null && cardList.size() > 0) {
                    customerProductDetailMemberCardVO.setCustomerProductDetailMemberCard(cardList);
                }

                //税法直通车
                List<CustomerProductDetailThroughTrainTax> taxList = customerDbService.getThroughTrainTaxByOrderIdAndCph(productOrderId, customerOrderBackMoney.getFinishOrderProductNum()+"CCC");
                if (taxList != null && taxList.size() > 0) {
                    customerProductDetailMemberCardVO.setTaxList(taxList);
                }

                //兑换码
                List<CustomerProductDetailExchangeCode> codeList = customerDbService.getExchangeCodeByOrderIdAndCph(productOrderId, customerOrderBackMoney.getFinishOrderProductNum()+"CCC");
                if (codeList != null && codeList.size() > 0) {
                    customerProductDetailMemberCardVO.setCodeList(codeList);
                }

                //云顾问卡
                List<CustomerProductDetailYun> yunList = customerDbService.getYunByOrderIdAndCph(productOrderId, customerOrderBackMoney.getFinishOrderProductNum()+"CCC");
                if (yunList != null && yunList.size() > 0) {
                    customerProductDetailMemberCardVO.setYunList(yunList);
                }

                //充值卡
                List<CustomerProductDetailRechargeCode> rechargeCodeList = customerDbService.getRechargeCodeByOrderIdAndCph(productOrderId, customerOrderBackMoney.getFinishOrderProductNum()+"CCC");
                if (rechargeCodeList != null && rechargeCodeList.size() > 0) {
                    customerProductDetailMemberCardVO.setRechargeCodeList(rechargeCodeList);
                }

                //优惠劵
                List<CustomerProductDetailCoupon> couponsList = customerDbService.getCouponsByOrderIdAndCph(productOrderId, customerOrderBackMoney.getFinishOrderProductNum()+"CCC");
                if (couponsList != null && couponsList.size() > 0) {
                    customerProductDetailMemberCardVO.setCouponsList(couponsList);
                }
            }

            map.put("card",customerProductDetailMemberCardVO);

        }

        //部分回款
        if("4".equals(customerOrderBackMoney.getOrderStatus())) {
           List<CustomerOrderBfhkVO> list =  customerProductOrderDetailDbService.selectCustomerOrderBfhkVOList(productOrderId);
            if(orderDetailVO.getOrderSurcharge() != null) {
                CustomerOrderBfhkVO customerOrderBfhkVO = new CustomerOrderBfhkVO();
                customerOrderBfhkVO.setOrderBackMoneyId(orderBackMoneyId);
                customerOrderBfhkVO.setProductOrderId(productOrderId);
                customerOrderBfhkVO.setProductName("附加费用");
                customerOrderBfhkVO.setProductFinalPrice(orderDetailVO.getOrderSurcharge());
                list.add(customerOrderBfhkVO);
            }
            map.put("customerOrderBackMoney",list);
        }

        map.put("sqbz",customerOrderBackMoney.getSqbz());
        map.put("shbz",customerOrderBackMoney.getShbz());

        return map;
    }



    /**
     *财务-销总-退款详情
     * @param orderBackMoneyId 退款id
     * @param productOrderId 订单id
     * @return
     */
    @Override
    public Map<String, Object> xzCustomerOrderBackMoneyDetail(String orderBackMoneyId, String productOrderId) {
        Map<String, Object> map = new HashMap<>();

        //订单详细信息
        OrderDetailVO orderDetailVO = customerProductOrderDbService.selectBackOrderDetail(orderBackMoneyId);

        //退款明细
        CustomerOrderBackMoney customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(orderBackMoneyId);

        map.put("order",orderDetailVO);

        ReturnMoney returnMoney = customerProductOrderDbService.selectReturnByRoyaltyStatus(productOrderId,1);
        if(returnMoney != null) {
            map.put("royaltyStatus","已发放");
        }else{
            map.put("royaltyStatus","未发放");
        }

        //已完成
        if("2".equals(customerOrderBackMoney.getOrderStatus())) {
            List<CustomerOrderBackMoney> list = new ArrayList<>();
            list.add(customerOrderBackMoney);
            map.put("customerOrderBackMoney",list);
        }

        //部分回款
        if("4".equals(customerOrderBackMoney.getOrderStatus())) {
            List<CustomerOrderBfhkVO> list =  customerProductOrderDetailDbService.selectCustomerOrderBfhkVOList(productOrderId);
            if(orderDetailVO.getOrderSurcharge() != null) {
                CustomerOrderBfhkVO customerOrderBfhkVO = new CustomerOrderBfhkVO();
                customerOrderBfhkVO.setOrderBackMoneyId(orderBackMoneyId);
                customerOrderBfhkVO.setProductOrderId(productOrderId);
                customerOrderBfhkVO.setProductName("附加费用");
                customerOrderBfhkVO.setProductFinalPrice(orderDetailVO.getOrderSurcharge());
                list.add(customerOrderBfhkVO);
            }
            map.put("customerOrderBackMoney",list);
        }

        map.put("sqbz",customerOrderBackMoney.getSqbz());
        return map;
    }

    /**
     *财务-余额退款详情
     * @param orderBackMoneyId 退款id
     * @return
     */
    @Override
    public Map<String, Object> balanceBackMoneyDetail(String orderBackMoneyId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        Map<String, Object> map = new HashMap<>();

        //退款明细
        BalanceBackMoneyVO balanceBackMoneyVO = customerProductOrderDbService.selectBalanceBackMoneyDetail(orderBackMoneyId);

        //退款明细
        CustomerOrderBackMoney customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(orderBackMoneyId);

        //退款审批表
        CustomerOrderBackMoneyExamine examine = customerProductOrderDbService.selectOrderBackMoneyExamine(orderBackMoneyId);
        if(0 == customerOrderBackMoney.getBackStatus()) {
            if(examine == null) {
                examine = new CustomerOrderBackMoneyExamine();
                examine.setOrderBackMoneyExamineId(CommonUtils.getGUID());
                examine.setAdoptSituation(0);
                examine.setFzExamineStatus(0);
                examine.setCreatePeopleId(userAccount.getAccountId());
                examine.setCreateTm(new Date());
                examine.setUpdatePeopleId(userAccount.getAccountId());
                examine.setUpdateTm(new Date());
                examine.setAccountId(userAccount.getAccountId());
                examine.setCompanyId(userAccount.getCompanyId());
                examine.setOrderBackMoneyId(orderBackMoneyId);
                customerProductOrderDbService.addCustomerOrderBackMoneyExamine(examine);
            }
        }

        map.put("balanceBackMoneyVO",balanceBackMoneyVO);
        map.put("orderBackMoneyExamine",examine);


        if(0 == examine.getAdoptSituation()) {
            map.put("status",examine.getFzExamineStatus());
        }else if(1 == examine.getAdoptSituation()) {
            map.put("status",examine.getKfExamineStatus());
        }else if(2 == examine.getAdoptSituation()) {
            map.put("status",examine.getXzExamineStatus());
        }else if(3 == examine.getAdoptSituation()) {
            map.put("status",examine.getWlbExamineStatus());
        }else if(4 == examine.getAdoptSituation()) {
            map.put("status",examine.getCwExamineStatus());
        }else{
            map.put("status",null);
        }

        return map;
    }

    /**
     *财务-销总-余额退款详情  balance
     * @param orderBackMoneyId 退款id
     * @return
     */
    //@Override
    public Map<String, Object> xzBalanceBackMoneyDetail(String orderBackMoneyId) {
        Map<String, Object> map = new HashMap<>();
        //退款明细
        BalanceBackMoneyVO balanceBackMoneyVO = customerProductOrderDbService.selectBalanceBackMoneyDetail(orderBackMoneyId);
        map.put("balanceBackMoneyVO",balanceBackMoneyVO);
        return map;
    }

    /**
     * 通过退款id查询退款
     * @param orderBackMoneyId 退款id
     * @return
     */
    @Override
    public CustomerOrderBackMoney getCustomerOrderMoneyDetail(String orderBackMoneyId) {
        return customerProductOrderDbService.getCustomerOrderMoneyDetail(orderBackMoneyId);
    }

    /**
     * 退款(财务端)
     * @Author bj
     * @Date  2021/7/27 9:27
     * @param backMoneyQO -退款产品信息
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String orderRefundFinance(BackMoneyQO backMoneyQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        CustomerOrderBackMoney customerOrderBackMoney = new CustomerOrderBackMoney();
        customerOrderBackMoney.setOrderBackMoneyId(backMoneyQO.getOrderBackMoneyId());
        customerOrderBackMoney.setBackNumber(backMoneyQO.getBackNumber());
        customerOrderBackMoney.setProductOrderId(backMoneyQO.getProductOrderId());
        customerOrderBackMoney.setFinishOrderProductNum(backMoneyQO.getFinishOrderProductNum());
        customerOrderBackMoney.setProductName(backMoneyQO.getProductName());
        customerOrderBackMoney.setProductOriginalPrice(backMoneyQO.getProductOriginalPrice());
        customerOrderBackMoney.setProductUnitPrice(backMoneyQO.getProductUnitPrice());
        customerOrderBackMoney.setProductMemberPrice(backMoneyQO.getProductMemberPrice());
        customerOrderBackMoney.setProductPreferentialPrice(backMoneyQO.getProductPreferentialPrice());
        customerOrderBackMoney.setProductFinalPrice(backMoneyQO.getProductFinalPrice());
        customerOrderBackMoney.setApplyBackMoney(backMoneyQO.getApplyBackMoney());
        customerOrderBackMoney.setFinishOrderProductNum(backMoneyQO.getFinishOrderProductNum());

        //通过退款id查询退款审核表
        CustomerOrderBackMoneyExamine examine = customerProductOrderDbService.selectOrderBackMoneyExamine(customerOrderBackMoney.getOrderBackMoneyId());
        CustomerOrderBackMoney orderBack = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
        CustomerProductOrder order = customerProductOrderDbService.selectCustomerProductOrderById(backMoneyQO.getProductOrderId());

        MessageAddQO message = new MessageAddQO();
        message.setAccountId(orderBack.getAccountId());
        message.setTheme("退款信息");
        message.setNewsType(2);
        message.setCompanyId(orderBack.getCompanyId());
        //分总
        if(0 == backMoneyQO.getAdoptSituation()) {
            examine.setFzExamineAccountId(userAccount.getAccountId());
            examine.setFzExamineUserName(userAccount.getUserName());
            examine.setFzExamineTm(new Date());
            examine.setFzExamineStatus(backMoneyQO.getBackStatus());
            examine.setFzExamineRemarks(backMoneyQO.getShbz());
            if(2 == backMoneyQO.getBackStatus()) {
                examine.setAdoptSituation(1);
                examine.setKfExamineStatus(0);
            }else{
                customerOrderBackMoney.setBackStatus(1);
            }
            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);

            message.setNewsDetail("您的有一笔退款，订单号为：" +
                    "<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=" + order.getProductOrderId() +"&contractId="+order.getContractId()+ "\">\n" +
                    "                        <span class=\"text\">"+ order.getOrderNumber()  +"</span>\n" +
                    "</a>\n" +
                    "当前分总审核已经完成,请 <span id=\"orderBackMoney\" data-orderBackMoneyId="+ orderBack.getOrderBackMoneyId()+" data-productOrderId=" + order.getProductOrderId()+"\" >点击查看</span>\n" +
                    ",系统消息请勿回复");
            messageService.addMessage(message);
        }



        //客服
        if(1 == backMoneyQO.getAdoptSituation()) {
            examine.setKfExamineAccountId(userAccount.getAccountId());
            examine.setKfExamineUserName(userAccount.getUserName());
            examine.setKfExamineTm(new Date());
            examine.setKfExamineStatus(backMoneyQO.getBackStatus());
            examine.setKfExamineRemarks(backMoneyQO.getShbz());

            if(2 == backMoneyQO.getBackStatus()) {
                examine.setAdoptSituation(2);
                examine.setXzExamineStatus(0);

                customerOrderBackMoney.setBackMoney(backMoneyQO.getBackMoney());
                customerOrderBackMoney.setServiceMoney(backMoneyQO.getServiceMoney());

                CustomerOrderBackMoney back = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
                UserAccount user = userAccountDbService.selectUserAccountByAccountId(back.getCreatePeopleId());
                HashMap<String, Object> paramMap = new HashMap<>();
                //
                paramMap.put("content", "<a href=\"https://www.dcrm.cn/front/xzExamine?orderBackMoneyId="+backMoneyQO.getOrderBackMoneyId() +"\">申请人"+user.getUserName()+"申请退款</a>");
                paramMap.put("uid", "heyi");
                /*paramMap.put("content", "<a href=\"http://192.168.0.164:8081/front/xzExamine?orderBackMoneyId="+backMoneyQO.getOrderBackMoneyId() +"\">申请人"+user.getUserName()+"申请退款</a>");
                paramMap.put("uid", "dcfl_15030978846");*/


                log.info("请求数据---"+paramMap);
                String res= HttpUtil.post("https://api.nsrjlb.com/crm/EnterpriseWeChat/sendCrm", paramMap);
                log.info("返回数据---"+res);

            }else{
                customerOrderBackMoney.setBackStatus(1);
            }
            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);

            message.setNewsDetail("您的有一笔退款，订单号为：" +
                    "<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=" + order.getProductOrderId() +"&contractId="+order.getContractId()+ "\">\n" +
                    "                        <span class=\"text\">"+ order.getOrderNumber()  +"</span>\n" +
                    "</a>\n" +
                    "当前客服部审核已经完成,请 <span id=\"orderBackMoney\" data-orderBackMoneyId="+ orderBack.getOrderBackMoneyId()+" data-productOrderId=" + order.getProductOrderId()+"\" >点击查看</span>\n" +
                    ",系统消息请勿回复");
            messageService.addMessage(message);

        }

        //网络部
        if(3 == backMoneyQO.getAdoptSituation()) {
            customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
            examine.setWlbExamineAccountId(userAccount.getAccountId());
            examine.setWlbExamineUserName(userAccount.getUserName());
            examine.setWlbExamineTm(new Date());
            examine.setWlbExamineStatus(backMoneyQO.getBackStatus());
            examine.setWlbExamineRemarks(backMoneyQO.getShbz());
            if(2 == backMoneyQO.getBackStatus()) {
                examine.setAdoptSituation(4);
                examine.setCwExamineStatus(0);
            }else{
                customerOrderBackMoney.setBackStatus(1);
            }

            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);

            message.setNewsDetail("您的有一笔退款，订单号为：" +
                    "<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=" + order.getProductOrderId() +"&contractId="+order.getContractId()+ "\">\n" +
                    "                        <span class=\"text\">"+ order.getOrderNumber()  +"</span>\n" +
                    "</a>\n" +
                    "当前网络部审核已经完成,请 <span id=\"orderBackMoney\" data-orderBackMoneyId="+ orderBack.getOrderBackMoneyId()+" data-productOrderId=" + order.getProductOrderId()+"\" >点击查看</span>\n" +
                    ",系统消息请勿回复");
            messageService.addMessage(message);

        }

        //财务部
        if(4 == backMoneyQO.getAdoptSituation()) {
            customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
            examine.setCwExamineAccountId(userAccount.getAccountId());
            examine.setCwExamineUserName(userAccount.getUserName());
            examine.setCwExamineTm(new Date());
            examine.setCwExamineRemarks(backMoneyQO.getShbz());
            examine.setCwExamineStatus(backMoneyQO.getBackStatus());
            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());

            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);

            customerOrderBackMoney.setBackMoney(backMoneyQO.getBackMoney());
            customerOrderBackMoney.setBackDate(new Date());
            //customerOrderBackMoney.setServiceMoney(backMoneyQO.getServiceMoney());
            List<ReturnMoney> reMoneyList = null;
            if(!StringUtils.isBlank(customerOrderBackMoney.getFinishOrderProductNum())) {
                reMoneyList = returnMoneyDbservice.selectFinishOrderProductNum(customerOrderBackMoney.getFinishOrderProductNum());
            }

            if(2 == backMoneyQO.getBackStatus()) {
                CustomerProductOrder customerOrder = customerProductOrderDbService.selectProductOrderById(customerOrderBackMoney.getProductOrderId());
                CustomerContract customerContract = customerContractDbService.selectContractById(customerOrder.getContractId());


                //订单状态为已完成的时候
                if("2".equals(customerOrder.getOrderStatus())) {

                    if(!"附加费用".equals(customerOrderBackMoney.getProductName())){

                        Integer de = backProduct(customerOrder.getProductOrderId(),customerOrderBackMoney.getFinishOrderProductNum());



                        //删除订单完成的产品的删除状态
                        FinishOrderProduct finish = finishOrderDBservice.selectFinshByProductNum(customerOrderBackMoney.getFinishOrderProductNum());

                        BigDecimal backMoney = customerProductOrderDbService.sumBackMoney(customerOrderBackMoney.getProductOrderId(),customerOrderBackMoney.getFinishOrderProductNum());
                        if(backMoney != null) {
                            if(finish.getProductFinalPrice().compareTo(backMoney.add(customerOrderBackMoney.getBackMoney())) == 0){
                                //finish.setDelFlag("1");
                                finish.setProductStatus("1");
                                finish.setUpdatePeopleId(userAccount.getAccountId());
                                finish.setUpdateTm(new Date());
                                finishOrderDBservice.updateFinishOrderProduct(finish);
                            }

                        }else{
                            if(finish.getProductFinalPrice().compareTo(customerOrderBackMoney.getBackMoney()) == 0){
                                //finish.setDelFlag("1");
                                finish.setProductStatus("1");
                                finish.setUpdatePeopleId(userAccount.getAccountId());
                                finish.setUpdateTm(new Date());
                                finishOrderDBservice.updateFinishOrderProduct(finish);
                            }
                        }






                        //回款扣除
                        collectionDeduction(customerOrderBackMoney,userAccount,finish,"产品");


                        CustomerProductOrderDetail customerProductOrderDetail = customerProductOrderDetailDbService.selectProductOrderDetailList(finish.getProductOrderDetailId());
                        if(customerProductOrderDetail.getProductQuantity() != 0 ) {
                            customerProductOrderDetail.setProductQuantity(customerProductOrderDetail.getProductQuantity()-1);
                            if(customerProductOrderDetail.getProductQuantity() == 0) {
                                customerProductOrderDetail.setProductStatus("1");
                            }
                            customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
                            customerProductOrderDetail.setUpdateTm(new Date());
                            customerProductOrderDetailDbService.updateCustomerProductOrderDetail(customerProductOrderDetail);
                        }



                    }

                    List<FinishOrderProduct> finishList = finishOrderDBservice.finishOrderBackProductList(customerOrder.getProductOrderId());

                    //退一个产品的时候,将合同和订单总金额减去申请退款的产品金额
                    if("附加费用".equals(customerOrderBackMoney.getProductName())) {
                        customerOrder.setSurchargeStatus("1");
                        //回款扣除
                        collectionDeduction(customerOrderBackMoney,userAccount,null,"附加费用");
                    }


                    customerOrder.setRefundStatus(0); //退款
                    customerContract.setRefundStatus(0); //退款

                    customerContract.setUpdatePeopleId(userAccount.getAccountId());
                    customerContract.setUpdateTm(new Date());
                    customerOrder.setUpdatePeopleId(userAccount.getAccountId());
                    customerOrder.setUpdateTm(new Date());


                    //完成订单产品数据为空,将合同订单改为已作废
                    if(finishList.size() == 0) {
                        if(customerOrder.getOrderSurcharge() == null || customerOrder.getOrderSurcharge().compareTo(BigDecimal.ZERO) == 0) {
                            //将合同订单作废
                            customerContract.setContractStatus("4");
                            customerOrder.setOrderStatus("3");
                        }else{
                            if("1".equals(customerOrder.getSurchargeStatus())) {
                                //将合同订单作废
                                customerContract.setContractStatus("4");
                                customerOrder.setOrderStatus("3");
                            }
                        }
                    }

                }

                if("4".equals(customerOrder.getOrderStatus())) {
                    //查询订单产品明细数据
                    List<CustomerProductOrderDetail> list = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(customerOrderBackMoney.getProductOrderId(), "4");
                    for(CustomerProductOrderDetail customerProductOrderDetail : list){
                        customerProductOrderDetail.setProductStatus("1");
                        customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
                        customerProductOrderDetail.setUpdateTm(new Date());
                        customerProductOrderDetailDbService.updateCustomerProductOrderDetail(customerProductOrderDetail);
                    }

                    List<FinishOrderProduct> finishList = finishOrderDBservice.finishList(customerOrder.getProductOrderId());
                    for(FinishOrderProduct finishOrderProduct : finishList) {
                        finishOrderProduct.setProductStatus("1");
                        finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
                        finishOrderProduct.setUpdateTm(new Date());
                        finishOrderDBservice.updateFinishOrderProduct(finishOrderProduct);
                    }

                    List<ReturnMoney> moneyList = returnMoneyDbservice.selectMoneyByOrderId(customerOrder.getProductOrderId());
                    for(ReturnMoney returnMoney : moneyList) {
                        Date data = returnMoney.getArriveTime();
                        BigDecimal arriveMoney = returnMoney.getArriveMoney();
                        returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                        returnMoney.setArriveTime(customerOrderBackMoney.getBackDate());
                        returnMoney.setArriveNum("RM"+ String.valueOf(new Date().getTime()));
                        returnMoney.setArriveMoney(new BigDecimal("0").subtract(returnMoney.getArriveMoney()));
                        returnMoney.setCreateBy(userAccount.getAccountId());
                        returnMoney.setCreateTm(new Date());
                        returnMoney.setUpdateBy(userAccount.getAccountId());
                        returnMoney.setUpdateTm(new Date());
                        returnMoney.setBackDate(customerOrderBackMoney.getBackDate());
                        returnMoney.setIsBack(1);
                        returnMoney.setScoreMoney(new BigDecimal("0").subtract(returnMoney.getScoreMoney()));
                        returnMoneyDbservice.addReturnMoney(returnMoney);



                        ReturnMoneyVO returnMoneyVO = new ReturnMoneyVO();

                        returnMoneyVO.setReturnMoneyId(returnMoney.getReturnMoneyId());
                        returnMoneyVO.setArriveMoney(returnMoney.getArriveMoney());
                        addReturnMoneyLog(returnMoneyVO,returnMoney.getArriveMoney(),userAccount.getAccountId());

                        FinishOrderProduct finish = finishOrderDBservice.selectFinshByProductNum(returnMoney.getFinishOrderProductNum());
                        BigDecimal gradeMoney = finish.getGradeMoney();
                        if(gradeMoney == null) {
                            gradeMoney = new BigDecimal("0.0");
                        }
                        returnMoneyRedisService.delReturnMoney(data,userAccount.getCompanyId(),arriveMoney,gradeMoney);
                    }

                    customerContract.setRefundStatus(0); //退款
                    customerContract.setContractStatus("4");
                    customerOrder.setOrderStatus("3");
                    customerContract.setUpdatePeopleId(userAccount.getAccountId());
                    customerContract.setUpdateTm(new Date());

                    customerOrder.setRefundStatus(0); //退款
                    customerOrder.setUpdatePeopleId(userAccount.getAccountId());
                    customerOrder.setSurchargeStatus("1");
                    customerOrder.setUpdateTm(new Date());

                }

                customerContractDbService.updateCustomerContract(customerContract);
                customerProductOrderDbService.updateProductOrder(customerOrder);


                //余额支付   退款金额返回到客户的余额
                if("3".equals(customerOrder.getOrderPaymentWay())) {
                    Customer customer = customerDbService.selectCustomerById(customerOrder.getCustomerId());
                    customer.setCustomerWallet(customer.getCustomerWallet().add(customerOrderBackMoney.getBackMoney()));
                    customer.setUpdatePeopleId(userAccount.getAccountId());
                    customer.setUpdateTm(new Date());
                    customerDbService.updateCustomerById(customer);
                }

                customerOrderBackMoney.setBackStatus(2);
            }else{
                customerOrderBackMoney.setBackStatus(1);
            }

            message.setNewsDetail("您的有一笔退款，订单号为：" +
                    "<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=" + order.getProductOrderId() +"&contractId="+order.getContractId()+ "\">\n" +
                    "                        <span class=\"text\">"+ order.getOrderNumber()  +"</span>\n" +
                    "</a>\n" +
                    "当前财务审核已经完成,请 <span id=\"orderBackMoney\" data-orderBackMoneyId="+ orderBack.getOrderBackMoneyId()+" data-productOrderId=" + order.getProductOrderId()+"\" >点击查看</span>\n" +
                    ",系统消息请勿回复");
            messageService.addMessage(message);

        }

        customerOrderBackMoney.setShbz(customerOrderBackMoney.getShbz());
        customerOrderBackMoney.setUpdatePeopleId(userAccount.getAccountId());
        customerOrderBackMoney.setUpdateTm(new Date());
        Boolean bs = customerProductOrderDbService.updateCustomerOrderBackMoney(customerOrderBackMoney);
        if(bs) {
            return "SUCCESS";
        }else{
            return "FAIL";
        }
    }

    /**
     * 销总审核退款(财务端)
     * @Author bj
     * @Date  2021/7/27 9:27
     * @param backMoneyQO -退款产品信息
     */
    public Boolean xzOrderRefundFinance(BackMoneyQO backMoneyQO) {
        CustomerOrderBackMoney customerOrderBackMoney = customerProductOrderDbService.selectCustomerOrderBackMoneyById(backMoneyQO.getOrderBackMoneyId());

        //通过退款id查询退款审核表
        CustomerOrderBackMoneyExamine examine = customerProductOrderDbService.selectOrderBackMoneyExamine(customerOrderBackMoney.getOrderBackMoneyId());

        //销总
        if(2 == backMoneyQO.getAdoptSituation()) {
            if(examine != null) {
                examine.setXzExamineAccountId("xiaozong");
                examine.setXzExamineUserName("xiaozong");
                examine.setXzExamineTm(new Date());
                examine.setXzExamineStatus(backMoneyQO.getBackStatus());
                //examine.setXzExamineRemarks(backMoneyQO.getShbz());

                if(2 == backMoneyQO.getBackStatus()) {
                    examine.setWlbExamineStatus(0);
                    examine.setAdoptSituation(3);
                }else{
                    customerOrderBackMoney.setBackStatus(1);
                }
                examine.setUpdatePeopleId("xiaozong");
                examine.setUpdateTm(new Date());
                customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);
            }
        }

        CustomerOrderBackMoney orderBack = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
        CustomerProductOrder order = customerProductOrderDbService.selectCustomerProductOrderById(orderBack.getProductOrderId());

        MessageAddQO message = new MessageAddQO();
        message.setAccountId(orderBack.getAccountId());
        message.setTheme("退款信息");
        message.setNewsType(2);
        message.setCompanyId(orderBack.getCompanyId());
        message.setNewsDetail("您的有一笔退款，订单号为：" +
                "<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=" + order.getProductOrderId() +"&contractId="+order.getContractId()+ "\">\n" +
                "                        <span class=\"text\">"+ order.getOrderNumber()  +"</span>\n" +
                "</a>\n" +
                "当前销总审核已经完成,请 <span id=\"orderBackMoney\" data-orderBackMoneyId="+ orderBack.getOrderBackMoneyId()+" data-productOrderId=" + order.getProductOrderId()+"\" >点击查看</span>\n" +
                ",系统消息请勿回复");
        message.setBs("1");
        messageService.addMessage(message);

        customerOrderBackMoney.setBackDate(new Date());
        //customerOrderBackMoney.setUpdatePeopleId("xiaozong");
        customerOrderBackMoney.setUpdateTm(new Date());
        Boolean bs = customerProductOrderDbService.updateCustomerOrderBackMoney(customerOrderBackMoney);
        return bs;
    }

    /**
     * 余额退款(财务端)
     * @Author bj
     * @Date  2021/7/27 9:27
     * @param backMoneyQO -退款产品信息
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public String balanceRefundFinance(BackMoneyQO backMoneyQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        CustomerOrderBackMoney customerOrderBackMoney = new CustomerOrderBackMoney();
        customerOrderBackMoney.setOrderBackMoneyId(backMoneyQO.getOrderBackMoneyId());
        customerOrderBackMoney.setBackNumber(backMoneyQO.getBackNumber());
        customerOrderBackMoney.setApplyBackMoney(backMoneyQO.getApplyBackMoney());
        customerOrderBackMoney.setServiceMoney(backMoneyQO.getServiceMoney());
        customerOrderBackMoney.setBackMoney(backMoneyQO.getBackMoney());
        //通过退款id查询退款审核表
        CustomerOrderBackMoneyExamine examine = customerProductOrderDbService.selectOrderBackMoneyExamine(customerOrderBackMoney.getOrderBackMoneyId());
        //分总
        if(0 == backMoneyQO.getAdoptSituation()) {
            examine.setFzExamineAccountId(userAccount.getAccountId());
            examine.setFzExamineUserName(userAccount.getUserName());
            examine.setFzExamineTm(new Date());
            examine.setFzExamineStatus(backMoneyQO.getBackStatus());
            examine.setFzExamineRemarks(backMoneyQO.getShbz());
            if(2 == backMoneyQO.getBackStatus()) {
                examine.setAdoptSituation(1);
                examine.setKfExamineStatus(0);
            }else{
                customerOrderBackMoney.setBackStatus(1);
                updateCustomerWallet(backMoneyQO,userAccount.getAccountId());
            }
            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);
        }



        //客服
        if(1 == backMoneyQO.getAdoptSituation()) {
            examine.setKfExamineAccountId(userAccount.getAccountId());
            examine.setKfExamineUserName(userAccount.getUserName());
            examine.setKfExamineTm(new Date());
            examine.setKfExamineStatus(backMoneyQO.getBackStatus());
            examine.setKfExamineRemarks(backMoneyQO.getShbz());
            if(2 == backMoneyQO.getBackStatus()) {
                examine.setAdoptSituation(2);
                examine.setXzExamineStatus(0);
                examine.setUpdatePeopleId(userAccount.getAccountId());
                examine.setUpdateTm(new Date());
                customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);

                customerOrderBackMoney.setBackMoney(backMoneyQO.getBackMoney());
                customerOrderBackMoney.setServiceMoney(backMoneyQO.getServiceMoney());

                CustomerOrderBackMoney back = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
                UserAccount user = userAccountDbService.selectUserAccountByAccountId(back.getCreatePeopleId());
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("content", "<a href=\"https://www.dcrm.cn/front/xzBalanceExamine?orderBackMoneyId="+backMoneyQO.getOrderBackMoneyId() +"\">申请人"+user.getUserName()+"申请退款</a>");
                paramMap.put("uid", "heyi");
                //paramMap.put("content", "<a href=\"http://192.168.1.113:8081/front/xzBalanceExamine?orderBackMoneyId="+backMoneyQO.getOrderBackMoneyId() +"\">申请人"+user.getUserName()+"申请退款</a>");
                //paramMap.put("uid", "dcfl_15030978846");
                log.info("请求数据---"+paramMap);
                String res= HttpUtil.post("https://api.nsrjlb.com/crm/EnterpriseWeChat/sendCrm", paramMap);
                log.info("返回数据---"+res);

            }else{
                customerOrderBackMoney.setBackStatus(1);
                updateCustomerWallet(backMoneyQO,userAccount.getAccountId());
            }

            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);


        }

        //网络部
        if(3 == backMoneyQO.getAdoptSituation()) {
            customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
            examine.setWlbExamineAccountId(userAccount.getAccountId());
            examine.setWlbExamineUserName(userAccount.getUserName());
            examine.setWlbExamineTm(new Date());
            examine.setWlbExamineStatus(backMoneyQO.getBackStatus());
            examine.setWlbExamineRemarks(backMoneyQO.getShbz());
            if(2 == backMoneyQO.getBackStatus()) {
                examine.setAdoptSituation(4);
                examine.setCwExamineStatus(0);
            }else{
                customerOrderBackMoney.setBackStatus(1);
                updateCustomerWallet(backMoneyQO,userAccount.getAccountId());
            }

            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);
        }

        //财务部
        if(4 == backMoneyQO.getAdoptSituation()) {
            customerOrderBackMoney = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
            customerOrderBackMoney.setBackMoney(backMoneyQO.getBackMoney());
            customerOrderBackMoney.setServiceMoney(backMoneyQO.getServiceMoney());
            customerOrderBackMoney.setBackDate(new Date());

            examine.setCwExamineAccountId(userAccount.getAccountId());
            examine.setCwExamineUserName(userAccount.getUserName());
            examine.setCwExamineStatus(backMoneyQO.getBackStatus());
            examine.setCwExamineRemarks(backMoneyQO.getShbz());
            examine.setCwExamineTm(new Date());
            if(2 == backMoneyQO.getBackStatus()) {
                customerOrderBackMoney.setBackStatus(2);

                ReturnMoney returnMoney = new ReturnMoney();
                returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                returnMoney.setArriveTime(customerOrderBackMoney.getBackDate());
                returnMoney.setArriveNum("RM"+ String.valueOf(new Date().getTime()));
                returnMoney.setArriveMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney()));
                returnMoney.setProductName("普通充值");
                returnMoney.setCustomerId(customerOrderBackMoney.getCustomerId());
                returnMoney.setCustomerName(customerOrderBackMoney.getCustomerName());
                returnMoney.setCreateBy(userAccount.getAccountId());
                returnMoney.setCreateTm(new Date());
                returnMoney.setUpdateBy(userAccount.getAccountId());
                returnMoney.setUpdateTm(new Date());
                returnMoney.setBackDate(customerOrderBackMoney.getBackDate());
                returnMoney.setIsBack(1);
                returnMoney.setScoreMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney()));
                returnMoney.setSalesmanId(customerOrderBackMoney.getAccountId());
                returnMoney.setFilialeId(customerOrderBackMoney.getCompanyId());
                returnMoneyDbservice.addReturnMoney(returnMoney);

            }else{
                customerOrderBackMoney.setBackStatus(1);
                updateCustomerWallet(backMoneyQO,userAccount.getAccountId());
            }

            examine.setUpdatePeopleId(userAccount.getAccountId());
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);

        }

        customerOrderBackMoney.setShbz(customerOrderBackMoney.getShbz());
        customerOrderBackMoney.setUpdatePeopleId(userAccount.getAccountId());
        customerOrderBackMoney.setUpdateTm(new Date());
        Boolean bs = customerProductOrderDbService.updateCustomerOrderBackMoney(customerOrderBackMoney);
        if(bs) {
            return "SUCCESS";
        }else{
            return "FAIL";
        }

    }

    /**
     * 销总余额审核退款(财务端)
     * @Author bj
     * @Date  2021/7/27 9:27
     * @param backMoneyQO -退款产品信息
     */
    @Override
    public Boolean xzBalanceRefundFinance(BackMoneyQO backMoneyQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerOrderBackMoney customerOrderBackMoney = customerProductOrderDbService.selectCustomerOrderBackMoneyById(backMoneyQO.getOrderBackMoneyId());

        //通过退款id查询退款审核表
        CustomerOrderBackMoneyExamine examine = customerProductOrderDbService.selectOrderBackMoneyExamine(customerOrderBackMoney.getOrderBackMoneyId());

        //销总
        if(examine != null) {
            examine.setXzExamineAccountId("xiaozong");
            examine.setXzExamineUserName("xiaozong");
            examine.setXzExamineTm(new Date());
            examine.setXzExamineStatus(backMoneyQO.getBackStatus());

            if(2 == backMoneyQO.getBackStatus()) {
                examine.setWlbExamineStatus(0);
                examine.setAdoptSituation(3);
            }else{
                customerOrderBackMoney.setBackStatus(1);
                updateCustomerWallet(backMoneyQO,"xiaozong");
            }
            examine.setUpdatePeopleId("xiaozong");
            examine.setUpdateTm(new Date());
            customerProductOrderDbService.updateCustomerOrderBackMoneyExamine(examine);
        }


        customerOrderBackMoney.setBackDate(new Date());
        //customerOrderBackMoney.setUpdatePeopleId("xiaozong");
        customerOrderBackMoney.setUpdateTm(new Date());
        Boolean bs = customerProductOrderDbService.updateCustomerOrderBackMoney(customerOrderBackMoney);
        return bs;
    }

    /**
     * 补全之前退款的回款记录表
     */
    @Override
    public void repairReturnMoney() {
        int i = 0;
        Date date = new Date();
        List<CustomerOrderBackMoney> list = customerProductOrderDbService.repairReturnMoney();
        for(CustomerOrderBackMoney customerOrderBackMoney : list) {
            List<ReturnMoney> returnList = returnMoneyDbservice.selectMoneyByOrderIdAndFinshNum(customerOrderBackMoney.getProductOrderId(),customerOrderBackMoney.getFinishOrderProductNum());
            if (returnList != null && returnList.size() > 0) {
                for(ReturnMoney returnMoney : returnList) {
                    returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                    returnMoney.setArriveTime(customerOrderBackMoney.getBackDate());
                    returnMoney.setArriveNum("RM" + String.valueOf(new Date().getTime()));
                    returnMoney.setArriveMoney(new BigDecimal("0").subtract(returnMoney.getArriveMoney()));
                    returnMoney.setCreateBy(customerOrderBackMoney.getCreatePeopleId());
                    returnMoney.setCreateTm(date);
                    returnMoney.setUpdateBy("e7ec17c6146a11ec9d8200163e04a0f3");
                    returnMoney.setUpdateTm(date);
                    returnMoney.setBackDate(customerOrderBackMoney.getBackDate());
                    returnMoney.setIsBack(1);
                    returnMoney.setScoreMoney(new BigDecimal("0").subtract(returnMoney.getScoreMoney()));
                    returnMoneyDbservice.addReturnMoney(returnMoney);
                    ReturnMoneyVO returnMoneyVO = new ReturnMoneyVO();

                    returnMoneyVO.setReturnMoneyId(returnMoney.getReturnMoneyId());
                    returnMoneyVO.setArriveMoney(returnMoney.getArriveMoney());
                    returnMoneyVO.setCreateTm(date);
                    addReturnMoneyLog(returnMoneyVO,returnMoney.getArriveMoney(),customerOrderBackMoney.getCreatePeopleId());
                    i+=1;
                }
            }
        }
        log.info("插入数据----------" + i);
    }

    public static void main(String[] args) {
        System.out.println("RM"+ String.valueOf(new Date().getTime()));
    }



    /**
     * 对比不一样的
     */
    @Override
    public void contrastFinish() {
        /*int i = 0;
        HashMap<String,Object> map = new HashMap<>();
        List<FinishOrderProductVO> beforeList = finishOrderProductDbService.selectFinish19();
        for(FinishOrderProductVO finish :beforeList) {
            map.put(finish.getProductOrderId() + "+" + finish.getFinishOrderProductNum()+ "+" + finish.getProductId(),finish);
        }
        List<FinishOrderProductVO> afterList = finishOrderProductDbService.selectFinish129();
        for (FinishOrderProductVO after : afterList) {
            if(map.containsKey(after.getProductOrderId() + "+" + after.getFinishOrderProductNum() + "+" + after.getProductId())) {
                map.remove(after.getProductOrderId() + "+" + after.getFinishOrderProductNum()+ "+" + after.getProductId());
            }

        }
        log.info("map的长度---------"+String.valueOf(map.size()));
        for (String key : map.keySet()) {
            log.info("key = " + key + ", value = " + new GsonBuilder().serializeNulls().create().toJson(map.get(key)));
        }*/




    }

    /**
     * 修改会员卡的起始时间和结束时间
     * @return
     */
    @Override
    public Boolean updateDate(String startTm,String endTm,String memberCardNumber) {
        CustomerProductDetailMemberCard memberCard = customerProductDetailMemberCardDbService.getCustomerProductDetailMemberCard(memberCardNumber);

        memberCard.setStartTm(formatTime(startTm));
        memberCard.setEndTm(formatTime(endTm));
        memberCard.setUpdateTm(new Date());
        return customerProductDetailMemberCardDbService.updateCard(memberCard);
    }

    /**
     * 补卡
     * @Author bj
     * @Date  2021/12/8 9:27
     */
    @Override
    public Boolean repairHairpin(String reqParam) {
        log.info("请求参数------"+reqParam);
        if (reqParam != null) {
            JSONObject jsonObject = JSON.parseObject(reqParam);
            JSONObject jsonObj = jsonObject.getJSONObject("reqParam");

            //产品编码
            String productCode = null;

            //订单
            CustomerProductOrder order = null;

            //用户id
            String accountId = null;

            //产品成交价
            BigDecimal productFinalPrice = null;

            //产品号
            String finishOrderProductNum = jsonObj.getString("finishOrderProductNum");
            if (!StringUtils.isBlank(finishOrderProductNum)) {
                FinishOrderProductVO finish = finishOrderProductDbService.selectFinishOrderProductByNumber(finishOrderProductNum);
                String productOrderId = finish.getProductOrderId();
                productCode = finish.getProductCode();
                productFinalPrice = finish.getProductFinalPrice();
                order = customerProductOrderDbService.selectCustomerProductOrderById(productOrderId);
                accountId = order.getCreatePeopleId();
            }

            UserAccount user = userAccountDbService.selectUserAccountByAccountId(accountId);


            //兑换码
            String exchangeCode = jsonObj.getString("exchangeCode");
            if (!StringUtils.isBlank(exchangeCode)) {
                List<ExchangeCodeVO> exList = JSONArray.parseArray(exchangeCode, ExchangeCodeVO.class);
                for (ExchangeCodeVO exchange : exList) {
                    CustomerProductDetailExchangeCode ex = new CustomerProductDetailExchangeCode();
                    ex.setExchangeCodeId(CommonUtils.getGUID());
                    ex.setExchangeCodeCrmId(exchange.getPromotionCode());
                    ex.setExchangeCodeName(exchange.getPromotionName());
                    ex.setExchangeCodePassword(exchange.getPassword());
                    ex.setCreatePeopleId(accountId);
                    ex.setCreateTm(new Date());
                    ex.setUpdatePeopleId(accountId);
                    ex.setUpdateTm(new Date());
                    ex.setProductOrderId(order.getProductOrderId());
                    ex.setProductCode(productCode);
                    ex.setFinishOrderProductNum(finishOrderProductNum);
                    customerDbService.addCustomerProductDetailExchangeCode(ex);
                }
            }

            //税法直通车
            String throughTrain = jsonObj.getString("throughTrain");
            if (!StringUtils.isBlank(throughTrain)) {
                List<ThroughTrainVO> array2 = JSONArray.parseArray(throughTrain, ThroughTrainVO.class);
                for (ThroughTrainVO vo : array2) {
                    CustomerProductDetailThroughTrainTax customerProductDetailThroughTrainTax = new CustomerProductDetailThroughTrainTax();
                    customerProductDetailThroughTrainTax.setThroughTrainTaxId(CommonUtils.getGUID());
                    customerProductDetailThroughTrainTax.setThroughTrainTaxCrmId(vo.getUserid());
                    customerProductDetailThroughTrainTax.setMemberCardNumber(vo.getUsername());
                    customerProductDetailThroughTrainTax.setMemberCardPassword(vo.getPassword());
                    customerProductDetailThroughTrainTax.setCreatePeopleId(accountId);
                    customerProductDetailThroughTrainTax.setCreateTm(new Date());
                    customerProductDetailThroughTrainTax.setUpdatePeopleId(accountId);
                    customerProductDetailThroughTrainTax.setUpdateTm(new Date());
                    customerProductDetailThroughTrainTax.setProductOrderId(order.getProductOrderId());
                    customerProductDetailThroughTrainTax.setProductCode(productCode);
                    customerProductDetailThroughTrainTax.setFinishOrderProductNum(finishOrderProductNum);
                    customerDbService.addCustomerProductDetailThroughTrainTax(customerProductDetailThroughTrainTax);
                }
            }
            String customerProductDetailMemberCardId = CommonUtils.getGUID();
            String number = "";
            //会员卡
            String userInfo = jsonObj.getString("userInfo");
            if (!StringUtils.isBlank(userInfo)) {
                List<CustomerCardVO> customerCardList = JSONArray.parseArray(userInfo, CustomerCardVO.class);
                CustomerContract customerContract = customerContractDbService.selectContractById(order.getContractId());
                for (CustomerCardVO customerCardVO : customerCardList) {
                    CustomerProductDetailMemberCard customerProductDetailMemberCard = new CustomerProductDetailMemberCard();

                    customerProductDetailMemberCard.setCustomerProductDetailMemberCardId(customerProductDetailMemberCardId);
                    customerProductDetailMemberCard.setMemberProductCode(productCode);
                    customerProductDetailMemberCard.setMemberCardId(customerCardVO.getUserid()); //crm的id
                    number = customerCardVO.getUsername();
                    customerProductDetailMemberCard.setMemberCardNumber(customerCardVO.getUsername());
                    customerProductDetailMemberCard.setMemberCardPassword(customerCardVO.getPassword());
                    customerProductDetailMemberCard.setStartTm(customerCardVO.getRuhuidata());
                    customerProductDetailMemberCard.setEndTm(customerCardVO.getYouxiaodata());
                    customerProductDetailMemberCard.setProductPrice(productFinalPrice);
                    customerProductDetailMemberCard.setCreatePeopleId(accountId);
                    customerProductDetailMemberCard.setCreateTm(new Date());
                    customerProductDetailMemberCard.setUpdatePeopleId(accountId);
                    customerProductDetailMemberCard.setUpdateTm(new Date());
                    customerProductDetailMemberCard.setAccountId(accountId);
                    customerProductDetailMemberCard.setCustomerId(order.getCustomerId());
                    customerProductDetailMemberCard.setContractId(order.getContractId());
                    customerProductDetailMemberCard.setContractNumber(customerContract.getContractNumber());
                    customerProductDetailMemberCard.setProductOrderId(order.getProductOrderId());
                    customerProductDetailMemberCard.setOrderNumber(order.getOrderNumber());
                    customerProductDetailMemberCard.setContactName(customerContract.getContactName());
                    customerProductDetailMemberCard.setPhone(customerContract.getContactDetails());
                    customerProductDetailMemberCard.setCompanyId(user.getCompanyId());
                    customerProductDetailMemberCard.setFinishOrderProductNum(finishOrderProductNum);
                    customerProductDetailMemberCard.setMaster(customerCardVO.getMaster());
                    customerDbService.addCustomerProductDetailMemberCard(customerProductDetailMemberCard);
                }
            }
            if (!StringUtils.isBlank(number)) {
                csdCustomerServiceImpl.getCardFrequency(number, customerProductDetailMemberCardId);
            }


            //云顾问卡
            String yunK = jsonObj.getString("user_yun");
            if (!StringUtils.isBlank(yunK)) {
                List<YunVO> yunList = JSONArray.parseArray(yunK, YunVO.class);
                for (YunVO Y : yunList) {
                    CustomerProductDetailYun yun = new CustomerProductDetailYun();
                    yun.setYunId(CommonUtils.getGUID());
                    yun.setYunCrmId(Y.getId());
                    yun.setYunCard(Y.getCard());
                    yun.setYunPassword(Y.getPassword());
                    yun.setCreatePeopleId(accountId);
                    yun.setCreateTm(new Date());
                    yun.setUpdatePeopleId(accountId);
                    yun.setUpdateTm(new Date());
                    yun.setProductOrderId(order.getProductOrderId());
                    yun.setProductCode(productCode);
                    yun.setFinishOrderProductNum(finishOrderProductNum);
                    customerDbService.addCustomerProductDetailYun(yun);
                }
            }

            //充值卡
            String rechargeCode = jsonObj.getString("rechargeCode");
            if (!StringUtils.isBlank(rechargeCode)) {
                List<RechargeCodeVO> exList = JSONArray.parseArray(rechargeCode, RechargeCodeVO.class);
                for (RechargeCodeVO recharge : exList) {
                    CustomerProductDetailRechargeCode ex = new CustomerProductDetailRechargeCode();
                    ex.setRechargeCodeId(CommonUtils.getGUID());
                    ex.setRechargeCodeCrmId(recharge.getRechargeCode());
                    ex.setRechargeCodeName(recharge.getRechargeName());
                    ex.setRechargeCodePassword(recharge.getPassword());
                    ex.setCreatePeopleId(accountId);
                    ex.setCreateTm(new Date());
                    ex.setUpdatePeopleId(accountId);
                    ex.setUpdateTm(new Date());
                    ex.setProductOrderId(order.getProductOrderId());
                    ex.setProductCode(productCode);
                    ex.setFinishOrderProductNum(finishOrderProductNum);
                    customerDbService.addCustomerProductDetailRechargeCode(ex);
                }
            }

            //优惠券
            String coupon = jsonObj.getString("coupon");
            if (!StringUtils.isBlank(coupon)) {
                List<CouponVO> exList = JSONArray.parseArray(coupon, CouponVO.class);
                for (CouponVO couponVO : exList) {
                    CustomerProductDetailCoupon c = new CustomerProductDetailCoupon();
                    c.setCouponId(CommonUtils.getGUID());
                    c.setCouponCodeCrmId(couponVO.getPromotionCode());
                    c.setCouponName(couponVO.getPromotionName());
                    if (!StringUtils.isBlank(couponVO.getPrice())) {
                        c.setPrice(couponVO.getPrice());
                    }
                    if (!StringUtils.isBlank(couponVO.getAbleproduct())) {
                        c.setAbleproduct(couponVO.getAbleproduct());
                    }
                    c.setCreatePeopleId(accountId);
                    c.setCreateTm(new Date());
                    c.setUpdatePeopleId(accountId);
                    c.setUpdateTm(new Date());
                    c.setProductOrderId(order.getProductOrderId());
                    c.setProductCode(productCode);
                    c.setFinishOrderProductNum(finishOrderProductNum);
                    customerDbService.addCustomerProductDetailCoupon(c);
                }
            }
        }
        return true;
    }

    public Date formatTime(String date) {
        //同一个Excel有不一样的时间格式……
        try{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return simpleDateFormat.parse(date);
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 余额退款不通过,余额返回
     */
    public void updateCustomerWallet(BackMoneyQO backMoneyQO,String accountId) {
        CustomerOrderBackMoney customerOrderMoneyDetail = customerProductOrderDbService.getCustomerOrderMoneyDetail(backMoneyQO.getOrderBackMoneyId());
        Customer customer = customerDbService.selectCustomerById(backMoneyQO.getCustomerId());
        if(customer !=null) {
            customer.setCustomerWallet(customer.getCustomerWallet().add(customerOrderMoneyDetail.getApplyBackMoney()));
            customer.setUpdateTm(new Date());
            customer.setUpdatePeopleId(accountId);
            customerDbService.updateCustomerById(customer);
        }
    }

    @Override
    public Integer backProduct(String orderId, String finishOrderProductNum) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //兑换码
        List<String> dhmList = new ArrayList<>();
        //税法直通车
        List<String> sfztcList = new ArrayList<>();
        //会员卡
        List<String> hykList = new ArrayList<>();
        //云顾问卡
        List<String> yList = new ArrayList<>();
        //充值卡
        List<String> czkList = new ArrayList<>();
        //优惠劵
        List<String> yhjList = new ArrayList<>();

        //兑换码
        List<CustomerProductDetailExchangeCode> exchangeCodeList = customerSendCodeDbService.customerProductDetailExchangeCodeByProductCodeList(orderId,finishOrderProductNum);
        if (exchangeCodeList != null && exchangeCodeList.size() > 0) {
            for(CustomerProductDetailExchangeCode vo : exchangeCodeList) {
                dhmList.add(vo.getExchangeCodeCrmId());
            }
        }

        //税法直通车
        List<CustomerProductDetailThroughTrainTax> taxList = customerSendCodeDbService.customerProductDetailThroughTrainTaxByProductCodeList(orderId,finishOrderProductNum);
        if (taxList != null && taxList.size() > 0) {
            for(CustomerProductDetailThroughTrainTax vo : taxList) {
                sfztcList.add(vo.getMemberCardNumber());
            }
        }

        //会员卡
        List<CustomerProductDetailMemberCard> memberList = customerSendCodeDbService.customerProductDetailMemberCardByProductCodeList(orderId,finishOrderProductNum);
        if (memberList != null && memberList.size() > 0) {
            for(CustomerProductDetailMemberCard vo : memberList) {
                hykList.add(vo.getMemberCardNumber());
            }
        }

        //云顾问卡
        List<CustomerProductDetailYun> yunList = customerSendCodeDbService.customerProductDetailYunByProductCodeList(orderId,finishOrderProductNum);
        if (yunList != null && yunList.size() > 0) {
            for(CustomerProductDetailYun vo : yunList) {
                yList.add(vo.getYunCard());
            }
        }

        //充值卡
        List<CustomerProductDetailRechargeCode> rechargeCodeList = customerSendCodeDbService.customerProductDetailRechargeCodeByProductCodeList(orderId,finishOrderProductNum);
        if (rechargeCodeList != null && rechargeCodeList.size() > 0) {
            for(CustomerProductDetailRechargeCode vo : rechargeCodeList) {
                czkList.add(vo.getRechargeCodeCrmId());
            }
        }

        //优惠劵
        List<CustomerProductDetailCoupon> couponList = customerSendCodeDbService.customerProductDetailCouponByProductCodeList(orderId,finishOrderProductNum);
        if (couponList != null && couponList.size() > 0) {
            for(CustomerProductDetailCoupon vo : couponList) {
                yhjList.add(vo.getCouponCodeCrmId());
            }
        }

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("exchangeCode", dhmList);
        paramMap.put("throughTrain", sfztcList);
        paramMap.put("userInfo", hykList);
        paramMap.put("user_yun", yList);
        paramMap.put("rechargeCode", czkList);
        paramMap.put("coupon", yhjList);
        //JSONObject jsons = new JSONObject(paramMap);
        String jsons = JSONObject.toJSONString(paramMap);
        //String s = JSONObject.toJSONString(map);
        log.info("请求数据---"+jsons);
        String res= HttpUtil.post("http://api.nsrjlb.com/crm/MemCard/refund", jsons);
        log.info("返回数据---"+res);
        JSONObject json = JSON.parseObject(res);
        Integer de = json.getInteger("code");


        if (exchangeCodeList != null && exchangeCodeList.size() > 0) {
            for(CustomerProductDetailExchangeCode vo : exchangeCodeList) {
                vo.setUpdatePeopleId(userAccount.getAccountId());
                vo.setUpdateTm(new Date());
                vo.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                customerSendCodeDbService.updateCustomerProductDetailExchangeCode(vo);
            }
        }

        if (taxList != null && taxList.size() > 0) {
            for(CustomerProductDetailThroughTrainTax vo : taxList) {
                vo.setUpdatePeopleId(userAccount.getAccountId());
                vo.setUpdateTm(new Date());
                vo.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                customerSendCodeDbService.updateCustomerProductDetailThroughTrainTax(vo);
            }
        }

        if (memberList != null && memberList.size() > 0) {
            for(CustomerProductDetailMemberCard vo : memberList) {
                vo.setUpdatePeopleId(userAccount.getAccountId());
                vo.setUpdateTm(new Date());
                vo.setVoidStatus(1);
                vo.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                customerSendCodeDbService.updateCustomerProductDetailMemberCard(vo);
            }
        }

        if (yunList != null && yunList.size() > 0) {
            for(CustomerProductDetailYun vo : yunList) {
                vo.setUpdatePeopleId(userAccount.getAccountId());
                vo.setUpdateTm(new Date());
                vo.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                customerSendCodeDbService.updateCustomerProductDetailYun(vo);
            }
        }

        if (rechargeCodeList != null && rechargeCodeList.size() > 0) {
            for(CustomerProductDetailRechargeCode vo : rechargeCodeList) {
                vo.setUpdatePeopleId(userAccount.getAccountId());
                vo.setUpdateTm(new Date());
                vo.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                customerSendCodeDbService.updateCustomerProductDetailRechargeCode(vo);
            }
        }

        if (couponList != null && couponList.size() > 0) {
            for(CustomerProductDetailCoupon vo : couponList) {
                vo.setUpdatePeopleId(userAccount.getAccountId());
                vo.setUpdateTm(new Date());
                vo.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState())));
                customerSendCodeDbService.updateCustomerProductDetailCoupon(vo);
            }
        }
        return de;
    }

    @Override
    public CustomerProductOrderVO selectCustomerProductOrderByNumber(String productOrderNumber) {
        CustomerProductOrderVO vo = customerProductOrderDbService.selectOrderByNumber(productOrderNumber);
        return vo;
    }

    /**
     * 向回款日志表中添加数据
     * @param returnMoneyVO  回款信息
     * @param money 剩余的金额
     * @param accountId 用户id
     */
    public void addReturnMoneyLog(ReturnMoneyVO returnMoneyVO,BigDecimal money,String accountId) {
        ReturnMoneyLog log = new ReturnMoneyLog();
        log.setReturnMoneyLogId(CommonUtils.getGUID());
        log.setReturnMoneyId(returnMoneyVO.getReturnMoneyId());
        log.setFormerData("金额:"+returnMoneyVO.getArriveMoney()+"；");
        log.setNewData("金额:"+money+"；");
        log.setOperatorType(3);
        log.setCreatePeopleId(accountId);
        log.setCreateTm(new Date());
        returnMoneyLogDbService.addReturnMoneyLog(log);
    }

    /**
     * 回款扣除
     * @param customerOrderBackMoney 退款
     * @param userAccount 用户信息
     * @param finish 完成
     */
    public void collectionDeduction(CustomerOrderBackMoney customerOrderBackMoney,UserAccount userAccount,FinishOrderProduct finish,String name) {
        //剩余金额
        BigDecimal money = customerOrderBackMoney.getBackMoney();

        BigDecimal zero = new BigDecimal("0.00");

        int a = 0;

        List<ReturnMoney> returnMoneyVOS = returnMoneyDbservice.selectFinishOrderProductNum(customerOrderBackMoney.getFinishOrderProductNum());

        if (returnMoneyVOS != null && returnMoneyVOS.size() > 0) {

            //for(ReturnMoney returnMoney : returnMoneyVOS) {
            ReturnMoney returnMoney = returnMoneyVOS.get(0);
            Date data = returnMoney.getArriveTime();

            returnMoney.setReturnMoneyId(CommonUtils.getGUID());
            returnMoney.setArriveTime(customerOrderBackMoney.getBackDate());
            returnMoney.setArriveNum("RM" + String.valueOf(new Date().getTime()));
            returnMoney.setArriveMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney()));
            returnMoney.setCreateBy(userAccount.getAccountId());
            returnMoney.setCreateTm(new Date());
            returnMoney.setUpdateBy(userAccount.getAccountId());
            returnMoney.setUpdateTm(new Date());
            returnMoney.setBackDate(customerOrderBackMoney.getBackDate());
            returnMoney.setIsBack(1);


            if(returnMoney.getScoreConvertRatio() != null) {
                returnMoney.setScoreMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney().multiply(returnMoney.getScoreConvertRatio())));
            }else{
                returnMoney.setScoreMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney()));
            }


            returnMoneyDbservice.addReturnMoney(returnMoney);
            ReturnMoneyVO returnMoneyVO = new ReturnMoneyVO();

            returnMoneyVO.setReturnMoneyId(returnMoney.getReturnMoneyId());
            returnMoneyVO.setArriveMoney(returnMoney.getArriveMoney());
            addReturnMoneyLog(returnMoneyVO,returnMoney.getArriveMoney(),userAccount.getAccountId());
            BigDecimal gradeMoney = finish.getGradeMoney();
            if(finish.getGradeMoney() == null) {
                gradeMoney = new BigDecimal("0.0");
            }
            returnMoneyRedisService.delReturnMoney(data,userAccount.getCompanyId(),money,gradeMoney);
        }else {
            Date data = null;
            ReturnMoney returnMoney = new ReturnMoney();
            returnMoney.setReturnMoneyId(CommonUtils.getGUID());
            returnMoney.setArriveTime(customerOrderBackMoney.getBackDate());
            returnMoney.setArriveNum("RM" + String.valueOf(new Date().getTime()));
            returnMoney.setArriveMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney()));
            returnMoney.setCreateBy(userAccount.getAccountId());
            returnMoney.setCreateTm(new Date());
            returnMoney.setUpdateBy(userAccount.getAccountId());
            returnMoney.setUpdateTm(new Date());
            returnMoney.setBackDate(customerOrderBackMoney.getBackDate());
            returnMoney.setIsBack(1);
            returnMoney.setScoreMoney(new BigDecimal("0").subtract(customerOrderBackMoney.getBackMoney()));


            if("附加费用".equals(name)) {
                CustomerOrderBackMoney BackMoney = customerProductOrderDbService.selectCustomerOrderBackMoneyById(customerOrderBackMoney.getOrderBackMoneyId());
                returnMoney.setSalesmanId(BackMoney.getAccountId());
                returnMoney.setFilialeId(BackMoney.getCompanyId());
                returnMoney.setRemark("附加费用退款");
            }else{
                returnMoney.setProductId(finish.getProductId());
                returnMoney.setProductNumber(finish.getProductCode());
                returnMoney.setProductName(finish.getProductName());
                returnMoney.setProductCategories(finish.getProductCategories());
                returnMoney.setFinishOrderProductId(finish.getFinishOrderProductId());
                returnMoney.setFinishOrderProductNum(finish.getFinishOrderProductNum());
                returnMoney.setOrderDetailType(finish.getOrderDetailType());
                returnMoney.setContractType(finish.getContractType());
                returnMoney.setContractNumber(finish.getContractNumber());
                returnMoney.setCustomerName(finish.getCustomerName());
                returnMoney.setOrderId(finish.getProductOrderId());
                returnMoney.setOrderNumber(finish.getOrderNumber());
                returnMoney.setSalesmanId(finish.getSalesmanId());
                returnMoney.setFilialeId(finish.getCompanyId());
            }

            returnMoney.setScoreConvertRatio(new BigDecimal("1"));
            returnMoney.setRoyaltyStatus(Integer.parseInt(finish.getRoyaltyStatus()));
            returnMoney.setRoyaltyMoney(zero);
            returnMoney.setRoyaltyRecordTime(customerOrderBackMoney.getBackDate());

            returnMoneyDbservice.addReturnMoney(returnMoney);
            ReturnMoneyVO returnMoneyVO = new ReturnMoneyVO();

            returnMoneyVO.setReturnMoneyId(returnMoney.getReturnMoneyId());
            returnMoneyVO.setArriveMoney(returnMoney.getArriveMoney());
            addReturnMoneyLog(returnMoneyVO,returnMoney.getArriveMoney(),userAccount.getAccountId());
            BigDecimal gradeMoney = finish.getGradeMoney();
            if(finish.getGradeMoney() == null) {
                gradeMoney = new BigDecimal("0.0");
            }
            returnMoneyRedisService.delReturnMoney(data,userAccount.getCompanyId(),money,gradeMoney);
        }
    }

    /*public static void main(String[] args) {
        //System.out.println("RM" + String.valueOf(new Date().getTime()));

        //String s = "{"rechargeCode":[],"userInfo":["5912101"],"throughTrain":["1504804","1521220"],"coupon\":[],\"user_yun\":[],\"exchangeCode\":[]}";
        //log.info("请求数据---"+s);
        //String res= HttpUtil.post("http://api.nsrjlb.com/crm/MemCard/refund", s);
        //log.info("返回数据---"+res);
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        Map<String,List<String>> map = new HashMap<>();
        map.put("aaa",list);
        String s = JSONObject.toJSONString(map);
        log.info(s);
    }*/

    /**
     * 订单详情-退款信息
     * @Author bj
     * @Date  2021/7/27 9:27
     */
    @Override
    public DhPageInfo<CustomerOrderBackMoneyVO> orderBackMoneyList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String productOrderId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<CustomerOrderBackMoneyVO> list = customerProductOrderDbService.orderBackMoneyList(productOrderId);

        PageInfo<CustomerOrderBackMoneyVO> pageInfo=new PageInfo<>(list);
        return new DhPageInfo<CustomerOrderBackMoneyVO>(pageInfo,list);
    }

    /**
     * 线上订单同步
     * @Author pym
     * @Date  2021/7/29 16:59
     * @param customerProductOrderAddQO 订单信息
     * @return {@link {java.lang.Boolean}}
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map<String,String> addOnlineOrder(CustomerProductOrderAddQO customerProductOrderAddQO) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        CustomerProduct customerProduct = null;
        String email = customerProductOrderAddQO.getEmail();//邮箱
        UserAccountManagerVO userAccount = userAccountDbService.getUserAccountByEmail(email);
        if (userAccount == null) { //账号不存在
            map.put("code", "UA00000");
            map.put("message", "账号不存在！");
            map.put("orderId", "");
            return map;
        }
        String zid = customerProductOrderAddQO.getZid();//专题id
        if (StringUtils.isBlank(zid)) {
            customerProduct = customerProductDbService.selectCustomerProductByCode("999");
        } else {
            customerProduct = customerProductDbService.selectCustomerProductByTopicId(zid);
        }
        if (customerProduct == null) {//非会员产品不存在
            map.put("code", "P000000");
            map.put("message", "非会员产品不存在！");
            map.put("orderId", "");
            return map;
        }
        String orderNumber = customerProductOrderAddQO.getOrderId();//商户订单号
        if (StringUtils.isBlank(orderNumber)) {//商户订单号不能为空
            map.put("code", "ON00000");
            map.put("message", "商户订单号不能为空！");
            map.put("orderId", "");
            return map;
        }
        CustomerProductOrder customerProductOrderRepeat = customerProductOrderDbService.isCustomerProductOrderRepeat(orderNumber);
        if (customerProductOrderRepeat != null) {//商户订单号已存在
            map.put("code", "ON00001");
            map.put("message", "商户订单号已存在！");
            map.put("orderId", "");
            return map;
        }
        CustomerContract customerContract = getCustomerContract(customerProductOrderAddQO, userAccount);
        CustomerProductOrder customerProductOrder = getCustomerProductOrder(customerProductOrderAddQO, userAccount, customerContract);
        customerContract.setOrderId(customerProductOrder.getProductOrderId());
        customerContractDbService.insertCustomerContract(customerContract);//新增非会员合同
        customerProductOrderDbService.insertProductOrder(customerProductOrder);//新增订单
        CustomerProductOrderDetail customerProductOrderDetail = getCustomerProductOrderDetail(customerProduct, customerProductOrder, customerProductOrderAddQO, userAccount);
        customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);//新增产品订单明细
        FinishOrderProduct finishOrderProduct = getFinishOrderProduct(customerProductOrderAddQO, customerProduct, customerProductOrder, customerProductOrderDetail, customerContract, userAccount);
        finishOrderDBservice.insertFinishOrderProduct(finishOrderProduct);//新增订单完成的产品
        ReturnMoney returnMoney = getReturnMoney(customerProductOrderAddQO, userAccount, customerContract, customerProductOrder, customerProduct, finishOrderProduct);
        returnMoneyDbservice.addReturnMoney(returnMoney);//插入回款表
        BigDecimal scoreMoney = Objects.nonNull(returnMoney.getScoreMoney()) ? returnMoney.getScoreMoney() : new BigDecimal(0.00);
        BigDecimal arriveMoney = Objects.nonNull(returnMoney.getArriveMoney()) ? returnMoney.getArriveMoney() : new BigDecimal(0.00);
        returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(), scoreMoney, arriveMoney, returnMoney.getArriveTime());//业绩、到款金额存redis
        map.put("code", "S000000");
        map.put("message", "保存成功！");
        map.put("orderId", customerProductOrder != null ? customerProductOrder.getProductOrderId() : "");
        return map;
    }

    /**
     * 通过订单id查询订单信息
     * @param orderId 订单id
     * @return
     */
    @Override
    public CustomerProductOrderVO getOrderInfoById(String orderId) {
        return customerProductOrderDbService.getOrderInfoById(orderId);
    }

    /**
     * 用户端-已完成订单退款产品列表
     * @param pageIndex 页码
     * @param pageSize 条数
     * @param sortName 分组名称
     * @param sortOrder 分组类型
     * @param orderId 订单id
     * @return
     */
    @Override
    public DhPageInfo<FinishOrderProduct> finishOrderBackProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<FinishOrderProduct> list = finishOrderDBservice.finishOrderBackProductList(orderId);


        PageInfo<FinishOrderProduct> pageInfo=new PageInfo<>(list);
        return new DhPageInfo<FinishOrderProduct>(pageInfo,list);
    }

    /**
     * 计算订单产品明细的价格
     * @param orderId 订单id
     * @return
     */
    @Override
    public BigDecimal orderProductDetailNumMoney(String orderId) {
        BigDecimal money = new BigDecimal(0.0);
        /*CustomerProductOrder customerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(orderId);
        List<CustomerProductOrderDetail> list = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId, "4");
        if(list != null && list.size() > 0){
            for(CustomerProductOrderDetail orderDetail : list){
                BigDecimal multiply = orderDetail.getProductFinalPrice().multiply(new BigDecimal(Integer.parseInt(orderDetail.getProductQuantity().toString())));
                money = money.add(multiply);
            }
        }
        if(customerProductOrder.getOrderSurcharge() != null) {
            money = money.add(customerProductOrder.getOrderSurcharge());
        }*/
        List<ReturnMoney> list = returnMoneyDbservice.selectMoneyByOrderId(orderId);
        for(ReturnMoney returnMoney : list){
            BigDecimal multiply = returnMoney.getArriveMoney();
            money = money.add(multiply);
        }

        return money;
    }

    /**
     * 财务首页订单数量统计
     * @return
     */
    @Override
    public FinanceIndexOrderInfoVO financeIndexOrderInfo(String companyId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if(StringUtils.isEmpty(companyId)){
            if ("4".equals(userAccount.getDeptId())){
                companyId = userAccount.getCompanyId();
            }
        }
        FinanceIndexOrderInfoVO resultVO = customerProductOrderDbService.financeIndexOrderInfo(companyId);
        if (StringUtils.isEmpty(companyId) && "3".equals(userAccount.getDeptId())){
            resultVO.setCompanyName("总部财务部");
        }else {
            SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(companyId);
            if (Objects.nonNull(sysCompany)){
                resultVO.setCompanyName(sysCompany.getCompanyName());
            }
        }
        return resultVO;
    }

    /**
     * 财务首页各种订单金额统计
     * @return
     */
    @Override
    public FinanceIndexOrderInfoListVO financeIndexOrderInfoList(String dateType,String companyId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        FinanceIndexOrderInfoListVO resultVO = new FinanceIndexOrderInfoListVO();
        if(StringUtils.isEmpty(companyId) && "4".equals(userAccount.getDeptId())){
            companyId = userAccount.getCompanyId();
        }
        Integer dateUnit = null;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("topMonth".equals(dateType)) {
                //本月
                dateUnit = 6;
            }
            if ("day".equals(dateType)) {
                //今天
                dateUnit = 5;
            }
        }
        BigDecimal moneyCount = returnMoneyDbservice.selectReturnMoneyCount(companyId,dateUnit);
        resultVO.setReturnMoneyCount(moneyCount);
        moneyCount = returnMoneyDbservice.selectBackMoneyCount(companyId,dateUnit);
        resultVO.setBackMoneyCount(moneyCount);
        //业绩金额
//        moneyCount = finishOrderDBservice.selectGradeMoneyCount(companyId,dateUnit);
        //充值金额
        moneyCount = customerPayDbService.selectPayMoneyCount(companyId,dateUnit);
        resultVO.setGradeMoneyCount(moneyCount);
        List<BigDecimal> countList= customerProductOrderDbService.selectOrderTypeReturnMoney(companyId,dateUnit,1);
        resultVO.setCourseProductCount(countList);
        countList= customerProductOrderDbService.selectOrderTypeReturnMoney(companyId,dateUnit,2);
        resultVO.setNewVipCount(countList);
        countList= customerProductOrderDbService.selectOrderTypeReturnMoney(companyId,dateUnit,4);
        resultVO.setReNewCount(countList);
        return resultVO;
    }

    /**
     * 财务首页-订单产品列表
     * @param dateType
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public DhPageInfo<FinanceIndexOrderProductVO> financeIndexOrderProductList(String dateType,String companyId, Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        if (StringUtils.isEmpty(companyId) && "4".equals(userAccount.getDeptId())){
            companyId = userAccount.getCompanyId();
        }
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("day".equals(dateType)) {
                //今天
                dateUnit = 5;
            }
        }
        List<FinanceIndexOrderProductVO> returnMoneyVOList= customerProductDbService.financeIndexOrderProductList(dateUnit,companyId);
        PageInfo<FinanceIndexOrderProductVO> pageInfo = new PageInfo<FinanceIndexOrderProductVO>(returnMoneyVOList);
        return new DhPageInfo<FinanceIndexOrderProductVO>(pageInfo, returnMoneyVOList);
    }

    /**
     * 获取回款
     * @Author pym
     * @Date  2021/7/30 11:06
     * @param customerProductOrderAddQO 订单信息
     * @param userAccount 账号信息
     * @param customerContract 合同
     * @param customerProductOrder 订单
     * @return {@link {com.crm.model.entity.returnMoney.ReturnMoney}}
     */
    private ReturnMoney getReturnMoney(CustomerProductOrderAddQO customerProductOrderAddQO, UserAccountManagerVO userAccount,
                                       CustomerContract customerContract, CustomerProductOrder customerProductOrder,
                                       CustomerProduct customerProduct, FinishOrderProduct finishOrderProduct) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        format.setLenient(false);
        ReturnMoney returnMoney = new ReturnMoney();
        returnMoney.setReturnMoneyId(CommonUtils.getGUID());//回款id
        //returnMoney.setSerial();//流水号
        //String arriveTime = customerProductOrderAddQO.getArriveTime();//到款时间
        //String orderCompleteTm = customerProductOrderAddQO.getOrderCompleteTm();
        /**2021-09-01 到款时间改成取订单创建时间，订单创建时间为空不处理*/
        String ctime = customerProductOrderAddQO.getCtime();
        if (isValidDate(ctime,"yyyy-MM-dd HH:mm:ss")) {
            returnMoney.setArriveTime(format.parse(ctime));
        }/* else if (isValidDate(orderCompleteTm,"yyyy-MM-dd HH:mm:ss")) {
            returnMoney.setArriveTime(format.parse(orderCompleteTm));
        } else {
            returnMoney.setArriveTime(new Date());
        }*/
        String price = customerProductOrderAddQO.getPrice();//订单金额
        if (StringUtils.isNotBlank(price)) {
            BigDecimal arriveMoney = new BigDecimal(price);
            returnMoney.setArriveMoney(arriveMoney.setScale(2,BigDecimal.ROUND_HALF_UP));//到款金额
        }
        returnMoney.setArriveUnitName("大成方略网络科技有限公司");//到款单位名称
        //returnMoney.setArriveType();//到款类型
        returnMoney.setArriveNum(String.valueOf(new Date().getTime()));//到款编号
        returnMoney.setArriveMethod(5);//到款方式（0银行回款 1现金 2余额支付 3线上支付 4转入额支付 5微信支付）
        returnMoney.setArriveIsAbolish(0);//到款是否作废（0 否 1 是）
        returnMoney.setArriveAccountType(2);//到款账号类型 0分公司 1北京财税研究院 2大成方略网络科技有限公司 3北京大成方略财务顾问有限公司 4北京大成方略纳税人俱乐部有限公司 5大成方略纳税人俱乐部股份有限公司
        //returnMoney.setPaymentUnit();//付款单位
        //returnMoney.setPaymentAccount();//付款账号
        //returnMoney.setPaymentBank();//付款银行
        //returnMoney.setContractStatus(0);//是否挂起（0否 1是）
        //returnMoney.setRenewContractStartTime();//续费合同开始日期
        returnMoney.setVipType(1);//会员类型（0会员 1非会员）
        //returnMoney.setIsRecordScore();//是否记录会员业绩（0否 1是）
        //returnMoney.setIsBack();//是否退款（0否 1是）
        //returnMoney.setBackDate();//退款日期
        //returnMoney.setRoyaltyStatus();//提成发放状态（1:已全部发放；2:部分发放;3:未发放）
        //returnMoney.setRoyaltyMoney();//提成金额
        //returnMoney.setRoyaltyRecordTime();//提成录入时间
        //returnMoney.setIsAbolish();//是否作废（0否 1是）
        //returnMoney.setSource();//来源渠道
        returnMoney.setContractId(customerContract.getContractId());//所属合同
        //returnMoney.setCustomerId();//所属客户
        returnMoney.setOrderId(customerProductOrder.getProductOrderId());//所属订单
        returnMoney.setSalesmanId(userAccount != null ? userAccount.getAccountId() : "");//所属业务员
        returnMoney.setFilialeId(userAccount != null ? userAccount.getCompanyId() : "");//所属分公司
        //returnMoney.setInvoiceStatus();//发票状态 0未开具 1部分开具 2 全部完成
        //returnMoney.setIsCheck();//是否检验（0否 1是）
        //returnMoney.setRemark();//备注
        returnMoney.setCreateTm(new Date());//创建时间
        returnMoney.setCreateBy(userAccount != null ? userAccount.getAccountId() : "");//创建人
        returnMoney.setUpdateTm(new Date());//更新时间
        returnMoney.setUpdateBy(userAccount != null ? userAccount.getAccountId() : "");//更新人
        returnMoney.setDelFlag(0);//删除标记（0未删除 1删除）
        //returnMoney.setDataSource();//0: 系统；1:导入
        //returnMoney.setMemberErrorData();//导入回款错误数据：0：否；1：是；
        if (customerProduct != null) {
            returnMoney.setProductId(customerProduct.getCustomerProductId());//产品id
            returnMoney.setProductName(customerProduct.getProductName());//产品名称
            returnMoney.setProductNumber(customerProduct.getProductCode());//产品编码
            BigDecimal performanceConversionRatio = customerProduct.getPerformanceConversionRatio();
            BigDecimal scoreConvertRatio = Objects.nonNull(performanceConversionRatio) ? performanceConversionRatio : new BigDecimal(1);
            returnMoney.setScoreConvertRatio(scoreConvertRatio);//业绩换算比例
            if (StringUtils.isNotBlank(price)) {
                BigDecimal scoreMoney = new BigDecimal(price).multiply(scoreConvertRatio);
                returnMoney.setScoreMoney(scoreMoney.setScale(2,BigDecimal.ROUND_HALF_UP));//业绩金额
            }
        } else {
            BigDecimal scoreConvertRatio = new BigDecimal(1);
            returnMoney.setScoreConvertRatio(scoreConvertRatio);//业绩换算比例
            if (StringUtils.isNotBlank(price)) {
                BigDecimal scoreMoney = new BigDecimal(price).multiply(scoreConvertRatio);
                returnMoney.setScoreMoney(scoreMoney.setScale(2,BigDecimal.ROUND_HALF_UP));//业绩金额
            }
        }
        returnMoney.setProductCategories("0");//产品分类:0:非会员:1:会员；
        returnMoney.setOrderDetailType("1");//订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型;4:兑换类型
        returnMoney.setContractType("1");//合同类型--1:非会员合同;2:会员新单合同;3:活动合同;4:会员续费合同5.兑换合同6.单品合同;7:会员单次合同
        returnMoney.setOrderNumber(customerProductOrder.getOrderNumber());//订单编号
        returnMoney.setContractNumber(customerContract.getContractNumber());//合同编号
        //returnMoney.setCustomerName();//客户名称
        returnMoney.setFinishOrderProductId(finishOrderProduct.getFinishOrderProductId());//finish表id
        returnMoney.setFinishOrderProductNum(finishOrderProduct.getFinishOrderProductNum());//产品号
        return returnMoney;
    }

    /**
     * 获取订单完成的产品
     * @Author pym
     * @Date  2021/7/29 16:04
     * @param customerProductOrderAddQO 订单信息
     * @param customerProduct 非会员产品
     * @param customerProductOrder 订单
     * @param customerProductOrderDetail 产品订单明细
     * @return {@link {com.crm.model.entity.finishOrderProduct.FinishOrderProduct}}
     */
    private FinishOrderProduct getFinishOrderProduct(CustomerProductOrderAddQO customerProductOrderAddQO, CustomerProduct customerProduct,
                                                     CustomerProductOrder customerProductOrder, CustomerProductOrderDetail customerProductOrderDetail,
                                                     CustomerContract customerContract, UserAccountManagerVO userAccount) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        format.setLenient(false);
        FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
        finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());//主键
        finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime()));//产品号
        String price = customerProductOrderAddQO.getPrice();//订单金额
        if (StringUtils.isNotBlank(price)) {
            BigDecimal productFinalPrice = new BigDecimal(price);
            finishOrderProduct.setProductFinalPrice(productFinalPrice.setScale(2,BigDecimal.ROUND_HALF_UP));//成交价
        }
        if (customerProduct != null) {
            finishOrderProduct.setProductId(customerProduct.getCustomerProductId());//产品id
            finishOrderProduct.setProductName(customerProduct.getProductName());//产品名称
            finishOrderProduct.setProductCode(customerProduct.getProductCode());//产品编码
            finishOrderProduct.setProductUnitPrice(customerProduct.getProductUnitPrice());//产品单价
            BigDecimal performanceConversionRatio = customerProduct.getPerformanceConversionRatio();
            BigDecimal scoreConvertRatio = Objects.nonNull(performanceConversionRatio) ? performanceConversionRatio : new BigDecimal(1);
            finishOrderProduct.setPerformanceConversionRatio(scoreConvertRatio);//业绩换算比例
            if (StringUtils.isNotBlank(price)) {
                BigDecimal gradeMoney = new BigDecimal(price).multiply(scoreConvertRatio);
                finishOrderProduct.setGradeMoney(gradeMoney.setScale(2,BigDecimal.ROUND_HALF_UP));//业绩金额
            }
        } else {
            BigDecimal scoreConvertRatio = new BigDecimal(1);
            finishOrderProduct.setPerformanceConversionRatio(scoreConvertRatio);//业绩换算比例
            if (StringUtils.isNotBlank(price)) {
                BigDecimal gradeMoney = new BigDecimal(price).multiply(scoreConvertRatio);
                finishOrderProduct.setGradeMoney(gradeMoney.setScale(2,BigDecimal.ROUND_HALF_UP));//业绩金额
            }
        }
        finishOrderProduct.setProductCategories("0");//产品分类:0:非会员:1:会员；
        finishOrderProduct.setOrderDetailType("1");//订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型;4:兑换类型
        //finishOrderProduct.setProductOriginalPrice();//产品原价
        //finishOrderProduct.setProductPreferentialPrice();//优惠价

        finishOrderProduct.setProductQuantity(1);//数量
        //finishOrderProduct.setOrderRelationId();//活动、赠品活动表主键
        finishOrderProduct.setProductOrderId(customerProductOrder.getProductOrderId());//订单id
        finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());//产品订单表id
        //finishOrderProduct.setExchangeMethod();//兑换方式：1-电子卡；2-兑换码；3-学习码；4-充值码;5-税法直通车学习卡;6:其他
        //finishOrderProduct.setRenewalStatus();//是否是续费合同 0 否 1是
        finishOrderProduct.setDelFlag("0");//删除标识 0 未删除 1已删除
        //finishOrderProduct.setProductStrokesServiceNumber();//当前服务次数
        //finishOrderProduct.setProductStrokesIndustryNumber();//当前行业会次数
        //String arriveTime = customerProductOrderAddQO.getArriveTime();//到款时间
        /**2021-09-01 到款时间改成取订单创建时间，订单创建时间为空不处理*/
        String ctime = customerProductOrderAddQO.getCtime();
        if (isValidDate(ctime,"yyyy-MM-dd HH:mm:ss")) {
            finishOrderProduct.setArriveTime(format.parse(ctime));
        }/* else {
            finishOrderProduct.setArriveTime(new Date());
        }*/
        finishOrderProduct.setSalesmanId(customerProductOrder.getCreatePeopleId());//所属业务员
        finishOrderProduct.setCompanyId(customerProductOrder.getAffiliationCompanyId());//所属公司
        finishOrderProduct.setOrderNumber(customerProductOrder.getOrderNumber());//订单编号
        finishOrderProduct.setContractNumber(customerContract.getContractNumber());//合同编号
        //finishOrderProduct.setCustomerName();//客户名称
        finishOrderProduct.setContractType("1");//合同类型--1:非会员合同;2:会员新单合同;3:活动合同;4:会员续费合同5.兑换合同6.单品合同;7:会员单次合同
        finishOrderProduct.setCreatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//创建人ID
        finishOrderProduct.setCreateTm(new Date());
        finishOrderProduct.setUpdatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//更新人ID
        finishOrderProduct.setUpdateTm(new Date());
        finishOrderProduct.setProductStatus("3");//产品状态 0 未回款 1退款 2部分回款 3已回款
        return finishOrderProduct;
    }

    /**
     * 获取产品订单明细
     * @Author pym
     * @Date  2021/7/29 15:56
     * @param customerProduct 非会员产品
     * @param customerProductOrder 订单
     * @return {@link {com.crm.model.entity.orderManager.CustomerProductOrderDetail}}
     */
    private CustomerProductOrderDetail getCustomerProductOrderDetail(CustomerProduct customerProduct, CustomerProductOrder customerProductOrder, CustomerProductOrderAddQO customerProductOrderAddQO, UserAccountManagerVO userAccount) {
        CustomerProductOrderDetail customerProductOrderDetail = new CustomerProductOrderDetail();
        customerProductOrderDetail.setProductOrderDetailId(CommonUtils.getGUID());
        customerProductOrderDetail.setProductCategories("0");//产品分类:0:非会员:1:会员；
        //customerProductOrderDetail.setProductOriginalPrice();//原价
        if (customerProduct != null) {
            customerProductOrderDetail.setOrderDetailName(customerProduct.getProductName());//名称(订单类型：1 则为产品名称；2/3则为活动名称)
            customerProductOrderDetail.setProductCode(customerProduct.getProductCode());//产品编码
            customerProductOrderDetail.setProductUnitPrice(customerProduct.getProductUnitPrice());//单价
            customerProductOrderDetail.setOrderRelationId(customerProduct.getCustomerProductId());//订单-关联产品、活动、赠品活动表主键
        }
        String price = customerProductOrderAddQO.getPrice();//订单金额
        if (StringUtils.isNotBlank(price)) {
            BigDecimal decimal = new BigDecimal(price);
            customerProductOrderDetail.setProductFinalPrice(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//产品成交价
        }
        //会员产品的优惠价等于会员价减成交价，要是为负值就默认为零 //非会员产品的优惠价等于产品原价减成交价，要是为负值就默认为零
        customerProductOrderDetail.setProductPreferentialPrice(BigDecimal.ZERO);
        customerProductOrderDetail.setProductQuantity(1);//数量
        customerProductOrderDetail.setProductOrderDetailType("1");//订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型
        customerProductOrderDetail.setCreatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//创建人ID
        customerProductOrderDetail.setCreateTm(new Date());
        customerProductOrderDetail.setUpdatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//更新人ID
        customerProductOrderDetail.setUpdateTm(new Date());
        customerProductOrderDetail.setProductOrderId(customerProductOrder.getProductOrderId());
        return customerProductOrderDetail;
    }

    /**
     * 获取订单
     * @Author pym
     * @Date  2021/7/29 15:46
     * @param customerProductOrderAddQO 订单信息
     * @param userAccount 账号信息
     * @param customerContract 合同
     * @return {@link {com.crm.model.entity.orderManager.CustomerProductOrder}}
     */
    private CustomerProductOrder getCustomerProductOrder(CustomerProductOrderAddQO customerProductOrderAddQO, UserAccountManagerVO userAccount, CustomerContract customerContract) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        format.setLenient(false);
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(CommonUtils.getGUID());
        customerProductOrder.setOrderType("0");//订单类型--0:非会员订单;1:会员订单（创建维护）
        customerProductOrder.setOrderPaymentWay("5");//支付方式--1:线上支付;2:线下支付;3:余额支付;4:银行汇款 （创建维护）;5:微信支付;
        //customerProductOrder.setOrderDiscountTotalAmount();//订单优惠总金额
        String price = customerProductOrderAddQO.getPrice();//订单金额
        if (StringUtils.isNotBlank(price)) {
            BigDecimal decimal = new BigDecimal(price);
            customerProductOrder.setOrderActualTotalAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//订单实际总金额 （创建   退款维护）
            customerProductOrder.setOrderTotalAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//订单总金额
            customerProductOrder.setPaidBackAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//已回款金额合计 （回款维护）
        }
        customerProductOrder.setOrderSurcharge(new BigDecimal("0.00"));//附加费用
        //customerProductOrder.setOrderSurchargeRemark();//附加费用备注
        //customerProductOrder.setContactPerson();//客户联系人
        //customerProductOrder.setBindMobilePhoneNumber();//客户联系方式
        //customerProductOrder.setCustomerEmail();//客户邮箱
        customerProductOrder.setContractType("1");//合同类型--1:非会员合同;2:会员新单合同;3:活动合同;4:会员续费合同5.兑换合同6.单品合同;7:会员单次合同
        customerProductOrder.setWhetherCoDevelopment("2");//是否合作开发--1:是;2:否
        customerProductOrder.setOrderNumber(customerProductOrderAddQO.getOrderId());//订单编号
        customerProductOrder.setWhetherSuspend("2");//是否挂起--1:是;2-否
        customerProductOrder.setOrderStatus("2");//订单状态--1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）
        String orderCompleteTm = customerProductOrderAddQO.getOrderCompleteTm();//订单完成时间
        if (isValidDate(orderCompleteTm,"yyyy-MM-dd HH:mm:ss")) {
            customerProductOrder.setOrderCompleteTm(format.parse(orderCompleteTm));//订单完成时间
        } else {
            customerProductOrder.setOrderCompleteTm(new Date());
        }
        customerProductOrder.setContractId(customerContract != null ? customerContract.getContractId() : "");
        customerProductOrder.setContractNumber(customerContract != null ? customerContract.getContractNumber() : "");//合同编号
        customerProductOrder.setAffiliationCompanyId(userAccount != null ? userAccount.getCompanyId() : "");//所属分公司--关联公司表ID
        //customerProductOrder.setCustomerId();//客户ID--关联客户表主键
        //customerProductOrder.setCustomerName();//客户名称
        customerProductOrder.setCreatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//所有人
        String createTm = customerProductOrderAddQO.getCtime();
        if (isValidDate(createTm,"yyyy-MM-dd HH:mm:ss")) {
            customerProductOrder.setCreateTm(format.parse(createTm));
        }/* else {
            customerProductOrder.setCreateTm(new Date());
        }*/
        customerProductOrder.setUpdatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//更新人ID
        customerProductOrder.setUpdateTm(new Date());
        //customerProductOrder.setRoyaltyStatus("");////提成发放状态（1:已全部发放；2:部分发放;3:未发放）
        String onlineOrderType = customerProductOrderAddQO.getOnlineOrderType();
        if ("线上订单".equals(onlineOrderType)) {
            customerProductOrder.setOnlineOrderType("1");
        } else if ("直播带货".equals(onlineOrderType)) {
            customerProductOrder.setOnlineOrderType("2");
        }
        return customerProductOrder;
    }

    /**
     * 获取非会员合同
     * @Author pym
     * @Date  2021/7/29 15:45
     * @param customerProductOrderAddQO 订单信息
     * @param userAccount 账号信息
     * @return {@link {com.crm.model.entity.contractManager.CustomerContract}}
     */
    private CustomerContract getCustomerContract(CustomerProductOrderAddQO customerProductOrderAddQO, UserAccountManagerVO userAccount) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        format.setLenient(false);
        CustomerContract customerContract = new CustomerContract();
        customerContract.setContractId(CommonUtils.getGUID());//合同id
        String contractNumber = String.valueOf(new Date().getTime());
        customerContract.setContractNumber(contractNumber);//合同编号
        customerContract.setContractStatus("2");//合同状态生效中
        //customerContract.setCustomerId();//客户ID
        //customerContract.setCustomerName();//客户名称
        customerContract.setContractType("1");//合同类型--1:非会员合同;2:会员新单合同;3:活动合同;4:会员续费合同5.兑换合同6.单品合同
        //customerContract.setOldContract("1");//是否是老合同：0:否;1:是
        //customerContract.setContractStartDate();//合同开始日期
        //customerContract.setContractEndDate(date.parse(contractEndDate));//合同结束日期
        String price = customerProductOrderAddQO.getPrice();//订单金额
        if (StringUtils.isNotBlank(price)) {
            BigDecimal decimal = new BigDecimal(price);
            customerContract.setContractActualTotalAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//合同实际总金额
            customerContract.setContractTotalPaymentAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//合同总回款金额
            customerContract.setContractTotalAmount(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//合同总金额
            customerContract.setContractReceivables(decimal.setScale(2,BigDecimal.ROUND_HALF_UP));//合同应收款（创建维护）
        }
        customerContract.setContractDiscountTotalAmount(new BigDecimal("0.00"));//合同优惠总金额（创建维护）
        customerContract.setPaymentNumber(1);//到款次数
        //只导入回款状态为已回款并且订单状态为生效中或者已结束的订单
        customerContract.setPaymentStatus("1");//回款状态：0-未回款；1-已回款；3-部分回款
        //String arriveTime = customerProductOrderAddQO.getArriveTime();//到款时间
        //String orderCompleteTm = customerProductOrderAddQO.getOrderCompleteTm();
        /**2021-09-01 到款时间改成取订单创建时间，订单创建时间为空不处理*/
        String ctime = customerProductOrderAddQO.getCtime();
        if (isValidDate(ctime,"yyyy-MM-dd HH:mm:ss")) {
            customerContract.setPayBackDate(format.parse(ctime));//回款日期
        }/* else if (isValidDate(orderCompleteTm,"yyyy-MM-dd HH:mm:ss")) {
            customerContract.setPayBackDate(format.parse(orderCompleteTm));//回款日期
        } else {
            customerContract.setPayBackDate(new Date());
        }*/
        customerContract.setWhetherCooperateDevelopment("0");//是否合作开发
        customerContract.setAffiliationCompanyId(userAccount != null ? userAccount.getCompanyId() : "");//所属分公司
        customerContract.setCreatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//所有人
        customerContract.setWhetherCheck("0");//是否会员合同:1 是；0-否
        customerContract.setPaymentMethod("6");//支付方式--2:线下支付;3:余额支付;4:转入额支付;5:余额＋转入额支付;6:微信支付;
        //customerContract.setCommissionStatus();//提成发放状态
        //customerContract.setContractRenewal();//合同续费
        customerContract.setContractCategory(0);//合同分类先算到合同列表中
        customerContract.setCreateTm(new Date());//创建时间
        customerContract.setUpdatePeopleId(userAccount != null ? userAccount.getAccountId() : "");//更新人ID
        customerContract.setUpdateTm(new Date());//更新时间
        customerContract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态
        customerContract.setWhetherHang("0");//是否挂起:1-是；0-否
        customerContract.setContractRenewal("1");//合同续费:1-正常合同；2-提前续费；3-延期续费（创建维护）
        customerContract.setContactReviewStatus("2");//合同审核状态：0-未审核；1-审核中；2-审核通过；3-审核失败 （审核维护）
        customerContract.setContactDetails(customerProductOrderAddQO.getMobile());//联系方式
        return customerContract;
    }

    /**
     * 判断一个字符串是否为合法日期
     * @Author pym
     * @param strDate -字符串
     * @return {@link {boolean}}
     */
    public boolean isValidDate(String strDate, String format) {
        boolean convertSuccess = true;
        SimpleDateFormat formatter  = new SimpleDateFormat(format);
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
            formatter.setLenient(false);
            Date date = formatter.parse(strDate);
        } catch (Exception e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 订单管理-订单列表-订单详情-产品详情
     * @Author pym
     * @Date  2021/9/6 14:40
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param productOrderId -产品订单表主键
     * @param productOrderDetailType -订单明细类型--1:产品类型;2:活动类型;3:赠品活动类型;4:兑换类型;5:补款升级
     * @return {@link {com.crm.common.model.DhPageInfo<com.crm.model.entity.finishOrderProduct.FinishOrderProduct>}}
     */
    @Override
    public DhPageInfo<FinishOrderProduct> selectOrderDetailFinishOrderProductList(Integer pageIndex, Integer pageSize, String productOrderId, String productOrderDetailType) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectOrderDetailFinishOrderProductList(productOrderId, productOrderDetailType);
        PageInfo<FinishOrderProduct> pageInfo = new PageInfo<FinishOrderProduct>(finishOrderProductList);
        return new DhPageInfo<FinishOrderProduct>(pageInfo, finishOrderProductList);
    }

    @Override
    public void orderToReturnMoney() {
        for (int pp=2;pp<5;pp++){
            List<CustomerProductOrderVO> list = customerProductOrderDbService.selectCustomerAllOrder(pp+"");
            for (int i=0;i<list.size();i++){
                log.info("开始拆分订单-- "+list.get(i).getProductOrderId());
                List<FinishOrderProduct> f = finishOrderDBservice.selectFinishOrderProductList(null,list.get(i).getProductOrderId());
                if (Objects.isNull(f) || f.size() == 0){
                    /*f.get(0).setDelFlag("1");
                    finishOrderDBservice.updateFinishOrderProduct(f.get(0));*/
                //}
                    CustomerContract contract = customerContractDbService.selectContractById(list.get(i).getContractId());
                    UserAccount userAccount = userAccountDbService.selectUserAccountByAccountId(list.get(i).getCreatePeopleId());
                    CustomerContractAddQO qo = new CustomerContractAddQO();
                    String contractNumber = null;
                    if (Objects.nonNull(contract)){
                        qo.setContractType(contract.getContractType());
                        qo.setWhetherCooperateDevelopment(contract.getWhetherCooperateDevelopment());
                        qo.setCustomerName(contract.getCustomerName());
                        contractNumber = contract.getContractNumber();
                    }
                    insertFinishOrderProduct(qo,list.get(i).getContractId(),contractNumber,list.get(i).getProductOrderId(),list.get(i).getOrderNumber(),userAccount);
                    List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList(null,list.get(i).getProductOrderId());
                    List<ReturnMoney> returnMoneyList = returnMoneyDbservice.selectMoneyByOrderId(list.get(i).getProductOrderId());
                    BigDecimal big = new BigDecimal("0");
                    int j = 0;
                    for (int k=0;k<finishOrderProductList.size();k++){
                        if (Objects.nonNull(finishOrderProductList.get(k).getProductFinalPrice())){
                            big =finishOrderProductList.get(k).getProductFinalPrice();
                        }
                        BigDecimal b = new BigDecimal("0");
                        for (int l = j;l<returnMoneyList.size();l++){
                            b = returnMoneyList.get(l).getArriveMoney();
                            ReturnMoney returnMoney =  new ReturnMoney();
                            if ("2".equals(list.get(i).getOrderStatus())){
                                returnMoney.setArriveType(0);
                            }else if ("4".equals(list.get(i).getOrderStatus())){
                                returnMoney.setArriveType(1);
                            }
                            returnMoney.setCustomerId(returnMoneyList.get(l).getCustomerId());
                            returnMoney.setFilialeId(returnMoneyList.get(l).getFilialeId());
                            returnMoney.setSalesmanId(returnMoneyList.get(l).getSalesmanId());
                            returnMoney.setArriveMoney(returnMoneyList.get(l).getArriveMoney());
                            returnMoney.setArriveTime(returnMoneyList.get(l).getArriveTime());
                            returnMoney.setArriveUnitName(returnMoneyList.get(l).getArriveUnitName());
                            returnMoney.setArriveMethod(returnMoneyList.get(l).getArriveMethod());
                            returnMoney.setArriveAccountType(returnMoneyList.get(l).getArriveAccountType());
                            returnMoney.setPaymentUnit(returnMoneyList.get(l).getPaymentUnit());
                            returnMoney.setPaymentAccount(returnMoneyList.get(l).getPaymentAccount());
                            returnMoney.setPaymentBank(returnMoneyList.get(l).getPaymentBank());
                            returnMoney.setVipType(returnMoneyList.get(l).getVipType());
                            returnMoney.setIsRecordScore(returnMoneyList.get(l).getIsRecordScore());
                            returnMoney.setIsBack(returnMoneyList.get(l).getIsBack());
                            returnMoney.setBackDate(returnMoneyList.get(l).getBackDate());
                            returnMoney.setOrderId(returnMoneyList.get(l).getOrderId());
                            returnMoney.setRemark(returnMoneyList.get(l).getRemark());
                            returnMoney.setCreateBy(returnMoneyList.get(l).getCreateBy());
                            returnMoney.setCreateTm(returnMoneyList.get(l).getCreateTm());
                            returnMoney.setDelFlag(returnMoneyList.get(l).getDelFlag());
                            returnMoney.setDataSource(returnMoneyList.get(l).getDataSource());
                            returnMoney.setMemberErrorData(returnMoneyList.get(l).getMemberErrorData());
                            returnMoney.setUpdateBy(returnMoneyList.get(l).getUpdateBy());
                            returnMoney.setUpdateTm(returnMoneyList.get(l).getUpdateTm());
                            returnMoney.setProductId(finishOrderProductList.get(k).getProductId());
                            returnMoney.setProductNumber(finishOrderProductList.get(k).getProductCode());
                            returnMoney.setFinishOrderProductId(finishOrderProductList.get(k).getFinishOrderProductId());
                            returnMoney.setFinishOrderProductNum(finishOrderProductList.get(k).getFinishOrderProductNum());
                            returnMoney.setProductName(finishOrderProductList.get(k).getProductName());
                            returnMoney.setProductCategories(finishOrderProductList.get(k).getProductCategories());
                            returnMoney.setOrderNumber(list.get(i).getOrderNumber());
                            returnMoney.setContractId(list.get(i).getContractId());
                            returnMoney.setContractNumber(contractNumber);
                            returnMoney.setOrderDetailType(finishOrderProductList.get(k).getOrderDetailType());
                            returnMoney.setCustomerName(list.get(i).getCustomerName());
                            returnMoney.setContractType(list.get(i).getContractType());
                            if (returnMoney.getArriveMoney().compareTo(big) == 0 || returnMoney.getArriveMoney().compareTo(big) == 1){
                                returnMoney.setArriveMoney(big);
                                countReturnMoneyScoreMoney(returnMoney,finishOrderProductList.get(k),contract,l);
                                if (returnMoneyList.get(l).getArriveMoney().compareTo(new BigDecimal("0")) == 0){
                                    j++;
                                }
                                returnMoneyList.get(l).setArriveMoney(b.subtract(big));
                                if (returnMoney.getArriveMoney().compareTo(big) == 1 || returnMoney.getArriveMoney().compareTo(big) == 0){
                                    big = new BigDecimal("0");
                                }
                            }else if (returnMoney.getArriveMoney().compareTo(big) == -1){
                                returnMoney.setArriveMoney(b);
                                countReturnMoneyScoreMoney(returnMoney,finishOrderProductList.get(k),contract,l);
                                big = big.subtract(returnMoney.getArriveMoney());
                                j++;
                                //returnMoneyList.get(l).setArriveMoney(big.subtract(returnMoney.getArriveMoney()));
                                //finishOrderProductList.get(k).setProductFinalPrice(big.subtract(returnMoney.getArriveMoney()));
                            }
                            finishOrderProductList.get(k).setProductStatus("2");
                            if (new BigDecimal("0").compareTo(big) == 0){
                                l = returnMoneyList.size();
                                finishOrderProductList.get(k).setProductStatus("3");
                            }
                            //计算业绩金额
                            if(Objects.isNull(finishOrderProductList.get(k).getPerformanceConversionRatio())){
                                finishOrderProductList.get(k).setGradeMoney(new BigDecimal("0"));
                            }else if (Objects.nonNull(finishOrderProductList.get(k).getGradeMoney())){
                                finishOrderProductList.get(k).setGradeMoney(finishOrderProductList.get(k).getGradeMoney().add(returnMoney.getArriveMoney().multiply(finishOrderProductList.get(k).getPerformanceConversionRatio()).divide(new BigDecimal("1"),2)));
                            }else {
                                finishOrderProductList.get(k).setGradeMoney(returnMoney.getArriveMoney().multiply(finishOrderProductList.get(k).getPerformanceConversionRatio()).divide(new BigDecimal("1"),2));
                            }
                            finishOrderDBservice.updateFinishOrderProduct(finishOrderProductList.get(k));
                            //countReturnMoneyScoreMoney(returnMoney,finishOrderProductList.get(k),contract,l);
                        }
                        /*CustomerProductOrder order = customerProductOrderDbService.selectProductOrderById(finishOrderProductList.get(k).getProductOrderId());
                        //对产品号
                        if (Objects.nonNull(order) && "2".equals(order.getOrderStatus())){
                            List<FinishOrderProductVO> finishNumberList = finishOrderProductDbService.selectFinishNumberByOrderIdAndProduct(list.get(i).getProductOrderId());
                            //for (int k=0;k<finishNumberList.size();k++){
                            List<FinishOrderProduct> finishOrderProduct=finishOrderProductDbService.selectFinishByOrderIdAndProductNumber(list.get(i).getProductOrderId(),null);
                            if (finishNumberList.size() == finishOrderProduct.size()){
                                for (int p=0;p<finishOrderProduct.size();p++){
                                    FinishOrderProduct finish = finishOrderProduct.get(p);
                                    System.out.println("pppp -----    "+ p);
                                    finish.setFinishOrderProductNum(finishNumberList.get(p).getFinishOrderProductNum());
                                    finishOrderProductDbService.updateFinishOrderProduct(finish);
                                }
                            }else {
                                System.out.println(order.getOrderNumber()+" 产品号匹配失败！！！！！！！！！！！！！！！！！！！！");
                            }
                        }*/
                    }
                }
                /*else {
                    for (int k =0;k<f.size();k++){
                        finishOrderDBservice.delFinishByOrderId(list.get(i).getProductOrderId());
                        returnMoneyDbservice.delFinishByOrderId(list.get(i).getProductOrderId());
                    }
                }*/
                log.info("拆分订单结束-- "+list.get(i).getProductOrderId());
            }
        }

    }

    public ReturnMoney countReturnMoneyScoreMoney(ReturnMoney returnMoney,FinishOrderProduct finish,CustomerContract contract,Integer num){
        returnMoney.setReturnMoneyId(CommonUtils.getGUID());
        returnMoney.setArriveNum("RM"+new Date().getTime()+num);
        BigDecimal ratio = finish.getPerformanceConversionRatio();
        returnMoney.setScoreConvertRatio(ratio);
        //如果业绩比例为0，业绩也金额也为0
        if (new BigDecimal("0.00").compareTo(ratio) == 0 || new BigDecimal("0").compareTo(ratio) == 0){
            returnMoney.setScoreMoney(new BigDecimal("0"));
        }
        BigDecimal arriveMoney = returnMoney.getArriveMoney();
        //是合作开发
        /*if ("1".equals(contract.getWhetherCooperateDevelopment())){

            List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contract.getContractId());
            for (int p=0;p < developerList.size();p++){
                returnMoney.setReturnMoneyId(CommonUtils.getGUID());
                returnMoney.setArriveNum("RM"+new Date().getTime()+num+p);
                UserAccount developerUser = userAccountDbService.selectUserAccountByUserId(developerList.get(p).getCoDeveloper());
                if (Objects.nonNull(ratio)){
                    returnMoney.setScoreMoney(arriveMoney.multiply(ratio).multiply(developerList.get(p).getAllocationRatio()).divide(new BigDecimal("1"),2));
                    returnMoney.setArriveMoney(arriveMoney.multiply(ratio).multiply(developerList.get(p).getAllocationRatio()).divide(new BigDecimal("1"),2));
                }
                returnMoney.setSalesmanId(developerUser.getAccountId());
                returnMoney.setFilialeId(developerUser.getCompanyId());
                returnMoney.setUpdateTm(new Date());
                //插入回款表
                returnMoneyDbservice.addReturnMoney(returnMoney);
                returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
            }
            returnMoney.setArriveMoney(arriveMoney);
        }else {
            if (Objects.nonNull(ratio)){
                returnMoney.setScoreMoney(arriveMoney.multiply(ratio));
            }
            returnMoney.setUpdateTm(new Date());
            returnMoneyDbservice.addReturnMoney(returnMoney);
            returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
        }*/

        if (Objects.nonNull(ratio)){
            returnMoney.setScoreMoney(arriveMoney.multiply(ratio));
        }
        returnMoney.setUpdateTm(new Date());
        returnMoneyDbservice.addReturnMoney(returnMoney);
        returnMoneyRedisService.returnMoneyToRedis(returnMoney.getFilialeId(),returnMoney.getScoreMoney(),returnMoney.getArriveMoney(),returnMoney.getArriveTime());
        return returnMoney;
    }

    public void insertFinishOrderProduct(CustomerContractAddQO customerContractAddQO, String contractId, String contractNumber, String orderId, String orderNumber,UserAccount userAccount){
        FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
        finishOrderProduct.setContractType(customerContractAddQO.getContractType());
        finishOrderProduct.setProductOrderId(orderId);
        finishOrderProduct.setOrderNumber(orderNumber);
        finishOrderProduct.setContractNumber(contractNumber);
        finishOrderProduct.setCooperateType(customerContractAddQO.getWhetherCooperateDevelopment());
        if (Objects.nonNull(userAccount)){
            finishOrderProduct.setSalesmanId(userAccount.getAccountId());
            finishOrderProduct.setCompanyId(userAccount.getCompanyId());
            finishOrderProduct.setCreatePeopleId(userAccount.getAccountId());
            finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
        }

        finishOrderProduct.setCustomerName(customerContractAddQO.getCustomerName());
        finishOrderProduct.setCreateTm(new Date());
        finishOrderProduct.setUpdateTm(new Date());

        //1、插入产品
        List<CustomerProductOrderDetail> productOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId, "1");
        productOrderDetailList.stream().forEach(customerProductOrderDetail -> {
            int num = customerProductOrderDetail.getProductQuantity();
            for (int i=0;i<num;i++){
                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                finishOrderProduct.setProductId(customerProductOrderDetail.getOrderRelationId());
                finishOrderProduct.setProductName(customerProductOrderDetail.getOrderDetailName());
                finishOrderProduct.setProductOriginalPrice(customerProductOrderDetail.getProductOriginalPrice());
                finishOrderProduct.setProductUnitPrice(customerProductOrderDetail.getProductUnitPrice());
                finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice());
                finishOrderProduct.setProductMemberPrice(customerProductOrderDetail.getProductMemberPrice());
                //优惠价不存
                finishOrderProduct.setProductCode(customerProductOrderDetail.getProductCode());
                finishOrderProduct.setProductQuantity(customerProductOrderDetail.getProductQuantity());
                finishOrderProduct.setOrderDetailType("1");
                finishOrderProduct.setProductCategories(customerProductOrderDetail.getProductCategories());
                finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());
                finishOrderProduct.setOrderRelationId(customerProductOrderDetail.getOrderRelationId());

                //如果是合作开发，产品号前面加个H
                if ("1".equals(customerContractAddQO.getWhetherCooperateDevelopment())){
                    finishOrderProduct.setFinishOrderProductNum("H" + new Date().getTime()+i);
                }else{
                    finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime())+i);
                }
                //业绩换算比例
                BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(),finishOrderProduct.getProductId());
                finishOrderProduct.setPerformanceConversionRatio(ratio);
                //Finish表产品号
/*                  if("1".equals(customerProductOrderDetail.getProductCategories())){
                      CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(customerProductOrderDetail.getOrderRelationId());
                      if(customerMemberProduct!=null){
                          finishOrderProduct.setProductStrokesServiceNumber(customerMemberProduct.getServiceNumber());
                      }
                  }*/
                int insertProduct = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
            }
        });

    }

}
